Hibernate List集合映射简单例子

jopen 8年前

Hibernate List集合映射简单例子

建两个相应的表:

email_list:

create table email_list(  id int(11) not null,  email_id int(11) not null,  email varchar(100) not null default ''  )engine=innodb default charset=gbk;

user_list:

create table user_list(  id int(11) not null auto_increment,  name varchar(100) not null default '',  primary key(id)  )engine=innodb default charset=gbk;
建立UserList.java实体类:

package collect.list;    import java.util.ArrayList;  import java.util.List;    public class UserList implements java.io.Serializable {   // Fields   private Integer id;   private String name;   private List emails = new ArrayList();     // Constructors   /** default constructor */   public UserList() {   }     /** full constructor */   public UserList(String name) {    this.name = name;   }     // Property accessors     public Integer getId() {    return this.id;   }     public void setId(Integer id) {    this.id = id;   }     public String getName() {    return this.name;   }     public void setName(String name) {    this.name = name;   }     public List getEmails() {    return emails;   }     public void setEmails(List emails) {    this.emails = emails;   }     public void addEmail(String email) {    emails.add(email);   }     public void removeEmail(String email) {    emails.remove(email);   }  }
建立映射文件UserList.hbm.xml:

<?xml version="1.0" encoding="utf-8"?>  <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  <!--       Mapping file autogenerated by MyEclipse Persistence Tools  -->  <hibernate-mapping>      <class name="collect.list.UserList" table="user_list" catalog="ssh">          <id name="id" type="java.lang.Integer">              <column name="id" />              <generator class="native" />          </id>          <property name="name" type="java.lang.String">              <column name="name" length="100" not-null="true" />          </property>          <list name="emails" table="email_list">           <key column="id"></key>           <index column="email_id"></index>           <element type="java.lang.String" column="email"></element>          </list>      </class>  </hibernate-mapping>

注解:其中List类型映射中<index>标签指定email_id字段记录List元素序号。

将该映射文件加入到Hibernate配置文件中,建立测试类Test.java:

package collect.list;    import java.util.List;  import org.hibernate.Session;  import org.hibernate.SessionFactory;  import org.hibernate.Transaction;  import org.hibernate.cfg.Configuration;    public class Test {     public static void main(String[] args) {    // Configuration管理Hibernate配置    Configuration config = new Configuration().configure();    // 根据Configuration建立 SessionFactory    // SessionFactory用来建立Session    SessionFactory sessionFactory = config.buildSessionFactory();      // 创建实例    UserList user1 = new UserList();    user1.setName("user1");    user1.addEmail("email1");    user1.addEmail("email2");    user1.addEmail("email1");    user1.addEmail("email3");      UserList user2 = new UserList();    user2.setName("user2");    user2.addEmail("email3");    user2.addEmail("email4");        // 添加数据    Session session = sessionFactory.openSession();    Transaction tx = null;    try {     tx = session.beginTransaction();     // INSERT到数据库     session.save(user1);     session.save(user2);     tx.commit();    } catch (RuntimeException e) {     if (tx != null)      tx.rollback();     throw e;    } finally {     session.close();    }      // 关闭sessionFactory    sessionFactory.close();     }    }
日志配置文件log4j.properties:(通过查看合适的日志,便于分析运行过程)

### direct log messages to stdout ###  log4j.appender.stdout=org.apache.log4j.ConsoleAppender  log4j.appender.stdout.Target=System.out  log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n    ### direct messages to file hibernate.log ###  #log4j.appender.file=org.apache.log4j.FileAppender  #log4j.appender.file.File=hibernate.log  #log4j.appender.file.layout=org.apache.log4j.PatternLayout  #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n    ### set log levels - for more verbose logging change 'info' to 'debug' ###    #log4j.rootLogger=warn, stdout  log4j.rootLogger=debug, stdout    #log4j.logger.org.hibernate=info  log4j.logger.org.hibernate=warn    ### log HQL query parser activity  #log4j.logger.org.hibernate.hql.ast.AST=debug    ### log just the SQL  log4j.logger.org.hibernate.SQL=debug    ### log JDBC bind parameters ###  #log4j.logger.org.hibernate.type=info  log4j.logger.org.hibernate.type=warn    ### log schema export/update ###  log4j.logger.org.hibernate.tool.hbm2ddl=warn    ### log HQL parse trees  log4j.logger.org.hibernate.hql=debug    ### log cache activity ###  log4j.logger.org.hibernate.cache=debug    ### log transaction activity  log4j.logger.org.hibernate.transaction=warn    ### log JDBC resource acquisition  log4j.logger.org.hibernate.jdbc=warn    ### enable the following line if you want to track down connection ###  ### leakages when using DriverManagerConnectionProvider ###  #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

运行结果:

控制台:

22:21:25,196 DEBUG SQL:346 - insert into ssh.user_list (name) values (?)
22:21:25,213 DEBUG SQL:346 - insert into ssh.user_list (name) values (?)
22:21:25,220 DEBUG SQL:346 - insert into email_list (id, email_id, email) values (?, ?, ?)
22:21:25,221 DEBUG SQL:346 - insert into email_list (id, email_id, email) values (?, ?, ?)
22:21:25,221 DEBUG SQL:346 - insert into email_list (id, email_id, email) values (?, ?, ?)
22:21:25,223 DEBUG SQL:346 - insert into email_list (id, email_id, email) values (?, ?, ?)
22:21:25,223 DEBUG SQL:346 - insert into email_list (id, email_id, email) values (?, ?, ?)
22:21:25,224 DEBUG SQL:346 - insert into email_list (id, email_id, email) values (?, ?, ?)

数据库:

Hibernate List集合映射简单例子

对比Set集合映射中没有email_id字段,就是因为Set集合中的元素是无序不重复的,而List集合中元素是有序可重复的。对于Set集合而言,email中重复的记录会被覆盖,这样一来email_id字段就没有意义了。而对于List集合,email联合字段email_id才可唯一确定一个有序email,emial_id相当于是List类型映射中<index>标签的index(索引,从下标0开始)了。