1.Set映射

DDL:

  1. CREATE TABLE user (
  2.     id INT(11) NOT NULL auto_increment PRIMARY KEY,
  3.     name VARCHAR(100) NOT NULL default ''
  4.  );

  5. CREATE TABLE email (
  6.     id INT(11) NOT NULL,
  7.     address VARCHAR(100) NOT NULL
  8. );

User.java

  1. package com.hb3.pack_11.model;

  2. import java.util.Set;

  3. public class User {

  4.     private Integer id;
  5.     private String name;
  6.     private Set<String> emails; 

  7.     public User() {
  8.     }

  9.     public Integer getId() {
  10.         return id;
  11.     }
  12.     public void setId(Integer id) {
  13.         this.id = id;
  14.     }
  15.     public String getName() {
  16.         return name;
  17.     }
  18.     public void setName(String name) {
  19.         this.name = name;
  20.     }
  21.     public Set<String> getEmails() {
  22.         return emails;
  23.     }
  24.     public void setEmails(Set<String> emails) {
  25.         this.emails = emails;
  26.     }
  27.     public void addEmail(String email) {
  28.         this.emails.add(email);
  29.     }
  30.     public void removeEmail(String email) {
  31.         this.emails.remove(email);
  32.     }
  33. }

User.hbm.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping 
  3.     PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  5. <hibernate-mapping>

  6.     <class name="com.hb3.pack_11.model.User" table="user">
  7.     
  8.         <id name="id" column="id" type="java.lang.Integer">
  9.             <generator class="native" />
  10.         </id>

  11.         <property name="name" column="name" type="java.lang.String" />
  12.         
  13.         <set name="emails" table="email">
  14.             <key column="id" />
  15.             <element type="java.lang.String" column="address" />
  16.         </set>
  17.     </class>
  18. </hibernate-mapping>

测试代码:

  1. package com.hb3.pack_11;

  2. import java.io.IOException;
  3. import java.sql.SQLException;
  4. import java.util.HashSet;

  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.hibernate.Transaction;
  8. import org.hibernate.cfg.Configuration;

  9. import com.hb3.pack_11.model.User;

  10. public class BusinessService {

  11.     public static void main(String[] args) throws IOException, SQLException {
  12.         
  13.         Configuration config = new Configuration().configure();
  14.         SessionFactory sessionFactory = config.buildSessionFactory();      
  15.         Session session = sessionFactory.openSession();

  16.      
  17.         User user1 = new User();
  18.         user1.setEmails(new HashSet<String>());
  19.         user1.setName("shenbin");
  20.         user1.addEmail("bluelazysb@hotmail.com");
  21.         user1.addEmail("bluelazysb@yahoo.com.cn");
  22.                 
  23.         User user2 = new User();
  24.         user2.setEmails(new HashSet<String>());
  25.         user2.setName("chenyan");
  26.         user2.addEmail("chenyan_xxxx@yahoo.com.cn");

  27.         Transaction tx = session.beginTransaction();            
  28.         session.save(user1);
  29.         session.save(user2); 
  30.         tx.commit();
  31.         
  32.         
  33.         session.close();
  34.         sessionFactory.close();
  35.     }
  36. }

Set的特点就是不能放置相同的物件在Set中。

也就是说,上述例子中,同一个User虽然可以对应多个emails,但是emails却不能有相同的(对同一个人而言)。

 

2.List映射

DDL:

  1. CREATE TABLE user (
  2.     id INT(11) NOT NULL auto_increment PRIMARY KEY,
  3.     name VARCHAR(100) NOT NULL default ''
  4. );

  5. CREATE TABLE item (
  6.     id INT(11) NOT NULL,
  7.     position INT(11) NOT NULL,
  8.     name VARCHAR(100) NOT NULL default ''
  9. );

User.java

  1. package com.hb3.pack_12.model;

  2. import java.util.List;

  3. public class User {

  4.     private Integer id;
  5.     private String name;
  6.     private List<String> items; 

  7.     public User() {
  8.     }

  9.     public Integer getId() {
  10.         return id;
  11.     }
  12.     public void setId(Integer id) {
  13.         this.id = id;
  14.     }
  15.     public String getName() {
  16.         return name;
  17.     }
  18.     public void setName(String name) {
  19.         this.name = name;
  20.     }
  21.     public List<String> getItems() {
  22.         return items;
  23.     }
  24.     public void setItems(List<String> items) {
  25.         this.items = items;
  26.     }
  27.     public void addItem(String item) {
  28.         items.add(item);
  29.     }
  30.     public void removeItem(String item) {
  31.         items.remove(item);
  32.     }
  33. }

User.hbm.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping 
  3.     PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  5. <hibernate-mapping> 

  6.     <class name="com.hb3.pack_12.model.User" table="user"> 
  7.     
  8.         <id name="id" column="id" type="java.lang.Integer"> 
  9.             <generator class="native"/> 
  10.         </id> 
  11.         
  12.         <property name="name" column="name" type="java.lang.String"/> 
  13.                 
  14.         <list name="items" table="item"> 
  15.             <key column="id"/> 
  16.             <index column="position"/> 
  17.             <element type="java.lang.String" column="name"/> 
  18.         </list> 
  19.         
  20.     </class> 
  21. </hibernate-mapping>

测试代码:

  1. package com.hb3.pack_12;

  2. import java.io.IOException;
  3. import java.sql.SQLException;
  4. import java.util.ArrayList;

  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.hibernate.Transaction;
  8. import org.hibernate.cfg.Configuration;

  9. import com.hb3.pack_12.model.User;

  10. public class BusinessService {

  11.     public static void main(String[] args) throws IOException, SQLException {
  12.         
  13.         Configuration config = new Configuration().configure();
  14.         SessionFactory sessionFactory = config.buildSessionFactory();      
  15.         Session session = sessionFactory.openSession();

  16.      
  17.         User user1 = new User();
  18.         user1.setItems(new ArrayList<String>());
  19.         user1.setName("shenbin");
  20.         user1.addItem("DC");
  21.         user1.addItem("CF Card");
  22.                 
  23.         User user2 = new User();
  24.         user2.setItems(new ArrayList<String>());
  25.         user2.setName("chenyan");
  26.         user2.addItem("CD");

  27.         Transaction tx = session.beginTransaction();            
  28.         session.save(user1);
  29.         session.save(user2); 
  30.         tx.commit();

  31.         
  32.         session.close();
  33.         sessionFactory.close();
  34.     }
  35. }

List是有序的结构。他在存储物品的时候还对物品所处的位置进行了记录。

 

 3.Bag映射

DDL:

  1. CREATE TABLE user (
  2.     id INT(11) NOT NULL auto_increment PRIMARY KEY,
  3.     name VARCHAR(100) NOT NULL default ''
  4. );

  5. CREATE TABLE item (
  6.     id INT(11) NOT NULL,
  7.     name VARCHAR(100) NOT NULL
  8. );

User.java

  1. package com.hb3.pack_13.model;

  2. import java.util.List;

  3. public class User {

  4.     private Integer id;
  5.     private String name;
  6.     private List<String> items; 

  7.     public User() {
  8.     }

  9.     public Integer getId() {
  10.         return id;
  11.     }
  12.     public void setId(Integer id) {
  13.         this.id = id;
  14.     }
  15.     public String getName() {
  16.         return name;
  17.     }
  18.     public void setName(String name) {
  19.         this.name = name;
  20.     }
  21.     public List<String> getItems() {
  22.         return items;
  23.     }
  24.     public void setItems(List<String> items) {
  25.         this.items = items;
  26.     }
  27.     public void addItem(String item) {
  28.         items.add(item);
  29.     }
  30.     public void removeItem(String item) {
  31.         items.remove(item);
  32.     }
  33. }

User.hbm.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping 
  3.     PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  5. <hibernate-mapping> 

  6.     <class name="com.hb3.pack_12.model.User" table="user"
  7.     
  8.         <id name="id" column="id" type="java.lang.Integer"
  9.             <generator class="native"/> 
  10.         </id> 
  11.         
  12.         <property name="name" column="name" type="java.lang.String"/> 
  13.                 
  14.         <bag name="items" table="item"
  15.             <key column="id"/> 
  16.             <element column="name" type="java.lang.String"/> 
  17.         </bag> 
  18.         
  19.     </class
  20. </hibernate-mapping>

测试代码:

  1. package com.hb3.pack_13;

  2. import java.io.IOException;
  3. import java.sql.SQLException;
  4. import java.util.ArrayList;

  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.hibernate.Transaction;
  8. import org.hibernate.cfg.Configuration;

  9. import com.hb3.pack_12.model.User;

  10. public class BusinessService {

  11.     public static void main(String[] args) throws IOException, SQLException {
  12.         
  13.         Configuration config = new Configuration().configure();
  14.         SessionFactory sessionFactory = config.buildSessionFactory();      
  15.         Session session = sessionFactory.openSession();

  16.      
  17.         User user1 = new User();
  18.         user1.setItems(new ArrayList<String>());
  19.         user1.setName("shenbin");
  20.         user1.addItem("Java Gossip");
  21.         user1.addItem("Java Gossip");
  22.         user1.addItem("Caxxx A80");
  23.                 
  24.         User user2 = new User();
  25.         user2.setItems(new ArrayList<String>());
  26.         user2.setName("chenyan");
  27.         user2.addItem("Snoppy world"); 
  28.         
  29.         Transaction tx = session.beginTransaction();
  30.         session.save(user1);
  31.         session.save(user2);
  32.         tx.commit();

  33.         
  34.         session.close();
  35.         sessionFactory.close();
  36.     }
  37. }

Bag是Hibernate自己提供的集合,他和Set的区别是它允许重复,他和List的区别是他不去管List容器中的順序。

然而,倘若要做下面的更新处理:

  1. Session session = sessionFactory.openSession();
  2. Transaction tx = session.beginTransaction();
  3. User user = (User) session.load(User.classnew Integer(1));
  4. user.removeItem("Java Gossip");
  5. tx.commit();
  6. session.close();

运行的SQL文为:

Hibernate: delete from item where id=?
Hibernate: insert into item (id, name) values (?, ?)
Hibernate: insert into item (id, name) values (?, ?)

 

由于Bag集合允许重复,当更新数据时,他无法知道需要更改的是重复数据中的哪比数据,所以采取全部删除后重新写入的方式。

然后,这显然是种没有效率的做法。

幸运的是,Hibernate提供idbag。借由在定义Bag映射时加上"collection-id",让Hibernate能确定需要更改的那条记录从而提高效率。

 

新建表格:

  1. CREATE TABLE user (
  2.     id INT(11) NOT NULL auto_increment PRIMARY KEY,
  3.     name VARCHAR(100) NOT NULL default ''
  4. );

  5. CREATE TABLE item (
  6.     cid CHAR(32) NOT NULL,
  7.     id INT(11) NOT NULL,
  8.     name VARCHAR(100) NOT NULL
  9. );

改写User.hbm.xml:

 

 

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping 
  3.     PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  5. <hibernate-mapping> 

  6.     <class name="com.hb3.pack_12.model.User" table="user"> 
  7.     
  8.         <id name="id" column="id" type="java.lang.Integer"> 
  9.             <generator class="native"/> 
  10.         </id> 
  11.         
  12.         <property name="name" column="name" type="java.lang.String"/> 
  13.                 
  14.         <idbag name="items" table="item"> 
  15.             <collection-id column="cid" type="java.lang.String">
  16.                 <generator class="uuid.hex"/>
  17.             </collection-id>
  18.             <key column="id"/>            
  19.             <element column="name" type="java.lang.String"/> 
  20.         </idbag>
  21.         
  22.     </class>
  23.     
  24. </hibernate-mapping>

测试代码:

  1. package com.hb3.pack_13;

  2. import java.io.IOException;
  3. import java.sql.SQLException;
  4. import java.util.ArrayList;

  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.hibernate.Transaction;
  8. import org.hibernate.cfg.Configuration;

  9. import com.hb3.pack_12.model.User;

  10. public class BusinessService {

  11.     public static void main(String[] args) throws IOException, SQLException {
  12.         
  13.         Configuration config = new Configuration().configure();
  14.         SessionFactory sessionFactory = config.buildSessionFactory();      
  15.         Session session = sessionFactory.openSession();

  16.      
  17.         User user1 = new User();
  18.         user1.setItems(new ArrayList<String>());
  19.         user1.setName("shenbin");
  20.         user1.addItem("Java Gossip");
  21.         user1.addItem("Java Gossip");
  22.         user1.addItem("Caxxx A80");
  23.                 
  24.         User user2 = new User();
  25.         user2.setItems(new ArrayList<String>());
  26.         user2.setName("chenyan");
  27.         user2.addItem("Snoppy world"); 
  28.         
  29.         Transaction tx = session.beginTransaction();
  30.         session.save(user1);
  31.         session.save(user2);
  32.         tx.commit();

  33.         
  34.         session.close();
  35.         session = sessionFactory.openSession();
  36.         
  37.         
  38.         tx = session.beginTransaction();
  39.         User user = (User) session.load(User.classnew Integer(1));
  40.         user.removeItem("Java Gossip");
  41.         tx.commit();
  42.         
  43.         
  44.         
  45.         session.close();
  46.         sessionFactory.close();
  47.     }
  48. }

SQL文的Log:

13:32:16,187  WARN ConfigurationFactory:127 - No configuration found. Configuring ehcache from ehcache-failsafe.xml  found in the classpath: jar:file:/D:/Java/MyEclipse%206.0/workspace/hb3demo/ehcache-1.2.3.jar!/ehcache-failsafe.xml
13:32:16,609  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
13:32:16,640  WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: insert into user (name) values (?)
Hibernate: insert into user (name) values (?)
Hibernate: insert into item (id, cid, name) values (?, ?, ?)
Hibernate: insert into item (id, cid, name) values (?, ?, ?)
Hibernate: insert into item (id, cid, name) values (?, ?, ?)
Hibernate: insert into item (id, cid, name) values (?, ?, ?)
Hibernate: select user0_.id as id0_0_, user0_.name as name0_0_ from user user0_ where user0_.id=?
Hibernate: select items0_.id as id0_, items0_.name as name0_, items0_.cid as cid0_ from item items0_ where items0_.id=?
Hibernate: delete from item where cid=?

 

4.Map映射

DDL:

  1. CREATE TABLE user (
  2.     id INT(11) NOT NULL auto_increment PRIMARY KEY,
  3.     name VARCHAR(100) NOT NULL default ''
  4. );

  5. CREATE TABLE item (
  6.     id INT(11) NOT NULL,
  7.     name VARCHAR(100) NOT NULL,
  8.     price decimal(10,2) NOT NULL
  9. );

User.java

  1. package com.hb3.pack_14.model;

  2. import java.math.BigDecimal;
  3. import java.util.Map;

  4. public class User {

  5.     private Integer id;
  6.     private String name;
  7.     private Map<String, BigDecimal> items; 

  8.     public User() {
  9.     }

  10.     public Integer getId() {
  11.         return id;
  12.     }
  13.     public void setId(Integer id) {
  14.         this.id = id;
  15.     }
  16.     public String getName() {
  17.         return name;
  18.     }
  19.     public void setName(String name) {
  20.         this.name = name;
  21.     }
  22.     public Map<String, BigDecimal> getItems() {
  23.         return items;
  24.     }
  25.     public void setItems(Map<String, BigDecimal> items) {
  26.         this.items = items;
  27.     }
  28.     public void addItem(String key, BigDecimal value) {
  29.         items.put(key, value);
  30.     }
  31.     public void removeItem(String key) {
  32.         items.remove(key);
  33.     }
  34. }

User.hbm.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping 
  3.     PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  5. <hibernate-mapping> 

  6.     <class name="com.hb3.pack_14.model.User" table="user"> 
  7.     
  8.         <id name="id" column="id" type="java.lang.Integer"> 
  9.             <generator class="native"/> 
  10.         </id> 
  11.         
  12.         <property name="name" column="name" type="java.lang.String"/> 
  13.                 
  14.         <map name="items" table="item">
  15.             <key column="id"/>
  16.             <map-key column="name" type="java.lang.String"/>
  17.             <element column="price" type="java.math.BigDecimal"/>
  18.         </map>
  19.         
  20.     </class>
  21.     
  22. </hibernate-mapping>

测试代码:

  1. package com.hb3.pack_14;

  2. import java.io.IOException;
  3. import java.math.BigDecimal;
  4. import java.sql.SQLException;
  5. import java.util.HashMap;

  6. import org.hibernate.Session;
  7. import org.hibernate.SessionFactory;
  8. import org.hibernate.Transaction;
  9. import org.hibernate.cfg.Configuration;

  10. import com.hb3.pack_14.model.User;


  11. public class BusinessService {

  12.     public static void main(String[] args) throws IOException, SQLException {
  13.         
  14.         Configuration config = new Configuration().configure();
  15.         SessionFactory sessionFactory = config.buildSessionFactory();      
  16.         Session session = sessionFactory.openSession();

  17.      
  18.         User user1 = new User();
  19.         user1.setItems(new HashMap<String, BigDecimal>());
  20.         user1.setName("shenbin");
  21.         user1.addItem("DC"new BigDecimal(100));
  22.         user1.addItem("CF Card"new BigDecimal(80));
  23.                 
  24.         User user2 = new User();
  25.         user2.setItems(new HashMap<String, BigDecimal>());
  26.         user2.setName("chenyan");
  27.         user2.addItem("CD"new BigDecimal(180));

  28.         Transaction tx = session.beginTransaction();            
  29.         session.save(user1);
  30.         session.save(user2); 
  31.         tx.commit();
  32.         
  33.         
  34.         session.close();
  35.         sessionFactory.close();
  36.     }
  37. }

注意:正常运行代码,需要修改hibernate.cfg.xml文件。

 

关于容器映射,还有如下说明。

1.內含 Component 的容器

DDL:

  1. CREATE TABLE user (
  2.     id INT(11) NOT NULL auto_increment PRIMARY KEY,
  3.     name VARCHAR(100) NOT NULL default ''
  4. );

  5. CREATE TABLE email (
  6.     id INT(11) NOT NULL,
  7.     address VARCHAR(100) NOT NULL
  8. );

MailAddress.java

  1. package com.hb3.pack_15.model;

  2. public class MailAddress {

  3.     private String address;

  4.     public MailAddress() {       
  5.     }
  6.     
  7.     public String getAddress() {
  8.         return address;
  9.     }
  10.     public void setAddress(String address) {
  11.         this.address = address;
  12.     }

  13.     public void sendMail() {
  14.         System.out.println("Send mail to " + address);
  15.     }
  16. }

User.java

  1. package com.hb3.pack_15.model;

  2. import java.util.Set;

  3. public class User {

  4.     private Integer id;
  5.     private String name;
  6.     private Set<MailAddress> emails; 

  7.     public User() {
  8.     }

  9.     public Integer getId() {
  10.         return id;
  11.     }

  12.     public void setId(Integer id) {
  13.         this.id = id;
  14.     }

  15.     public String getName() {
  16.         return name;
  17.     }

  18.     public void setName(String name) {
  19.         this.name = name;
  20.     }

  21.     public Set<MailAddress> getEmails() {
  22.         return emails;
  23.     }

  24.     public void setEmails(Set<MailAddress> emails) {
  25.         this.emails = emails;
  26.     }
  27.     
  28.     public void addEmail(MailAddress mailAddress) {
  29.         this.emails.add(mailAddress);
  30.     }
  31.     
  32.     public void removeEmail(MailAddress mailAddress) {
  33.         this.emails.remove(mailAddress);
  34.     }
  35. }

User.hbm.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE hibernate-mapping 
  3.     PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  4.     "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  5. <hibernate-mapping>

  6.     <class name="com.hb3.pack_15.model.User" table="user">
  7.     
  8.         <id name="id" column="id" type="java.lang.Integer">
  9.             <generator class="native" />
  10.         </id>

  11.         <property name="name" column="name" type="java.lang.String" />
  12.         
  13.         <set name="emails" table="email">
  14.             <key column="id" />
  15.             <composite-element class="com.hb3.pack_15.model.MailAddress"> 
  16.                 <property name="address" column="address"/> 
  17.             </composite-element>
  18.         </set>
  19.     </class>
  20. </hibernate-mapping>

测试代码:

  1. package com.hb3.pack_15;

  2. import java.io.IOException;
  3. import java.sql.SQLException;
  4. import java.util.HashSet;

  5. import org.hibernate.Session;
  6. import org.hibernate.SessionFactory;
  7. import org.hibernate.Transaction;
  8. import org.hibernate.cfg.Configuration;

  9. import com.hb3.pack_15.model.MailAddress;
  10. import com.hb3.pack_15.model.User;


  11. public class BusinessService {

  12.     public static void main(String[] args) throws IOException, SQLException {
  13.         
  14.         Configuration config = new Configuration().configure();
  15.         SessionFactory sessionFactory = config.buildSessionFactory();      
  16.         Session session = sessionFactory.openSession();

  17.      
  18.         User user = new User();
  19.         user.setName("shenbin");
  20.                 
  21.         user.setEmails(new HashSet<MailAddress>());
  22.         MailAddress mailAddress = new MailAddress();
  23.         mailAddress.setAddress("bluelazysb@hotmail.com");
  24.         user.addEmail(mailAddress);
  25.                 
  26.         mailAddress = new MailAddress();
  27.         mailAddress.setAddress("bluelazysb@yahoo.com.cn");
  28.         user.addEmail(mailAddress);
  29.                 
  30.         Transaction tx = session.beginTransaction();
  31.         session.save(user);
  32.         tx.commit();
  33.         
  34.         
  35.         session.close();
  36.         sessionFactory.close();
  37.     }
  38. }
  1. Session session = sessionFactory.openSession();
  2.         
  3. User user = (User) session.load(User.classnew Integer(1));
  4. Iterator iterator = user.getEmails().iterator();
  5. while(iterator.hasNext()) {
  6.     MailAddress mailAddress = (MailAddress) iterator.next();
  7.     mailAddress.sendMail();
  8. }
  9. session.close();

注意:当容器中所放置的物品为自定义的类型时需要使用Component容器。

 

2.容器的排序

我们知道,Set、Map、Bag是无序的,而List是有序的(所谓有序,就是存入容器的顺序会被反映到数据库中,与入库的顺序一致)。

实现请参照:http://www.javaworld.com.tw/confluence/pages/viewpage.action?pageId=3180

 

3.容器的延遲初始(Lazy Initialization)

参考资料:http://www.javaworld.com.tw/confluence/pages/viewpage.action?pageId=3181

特别留意Hibernate.initialize()的用法。



ExtJS教程- Hibernate教程-Struts2 教程-Lucene教程