1.Set映射
DDL:
- CREATE TABLE user (
- id INT(11) NOT NULL auto_increment PRIMARY KEY,
- name VARCHAR(100) NOT NULL default ''
- );
- CREATE TABLE email (
- id INT(11) NOT NULL,
- address VARCHAR(100) NOT NULL
- );
User.java
- package com.hb3.pack_11.model;
- import java.util.Set;
- public class User {
- private Integer id;
- private String name;
- private Set<String> emails;
- public User() {
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Set<String> getEmails() {
- return emails;
- }
- public void setEmails(Set<String> emails) {
- this.emails = emails;
- }
- public void addEmail(String email) {
- this.emails.add(email);
- }
- public void removeEmail(String email) {
- this.emails.remove(email);
- }
- }
User.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">
- <hibernate-mapping>
- <class name="com.hb3.pack_11.model.User" table="user">
-
- <id name="id" column="id" type="java.lang.Integer">
- <generator class="native" />
- </id>
- <property name="name" column="name" type="java.lang.String" />
-
- <set name="emails" table="email">
- <key column="id" />
- <element type="java.lang.String" column="address" />
- </set>
- </class>
- </hibernate-mapping>
测试代码:
- package com.hb3.pack_11;
- import java.io.IOException;
- import java.sql.SQLException;
- import java.util.HashSet;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import com.hb3.pack_11.model.User;
- public class BusinessService {
- public static void main(String[] args) throws IOException, SQLException {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- User user1 = new User();
- user1.setEmails(new HashSet<String>());
- user1.setName("shenbin");
- user1.addEmail("bluelazysb@hotmail.com");
- user1.addEmail("bluelazysb@yahoo.com.cn");
-
- User user2 = new User();
- user2.setEmails(new HashSet<String>());
- user2.setName("chenyan");
- user2.addEmail("chenyan_xxxx@yahoo.com.cn");
- Transaction tx = session.beginTransaction();
- session.save(user1);
- session.save(user2);
- tx.commit();
-
-
- session.close();
- sessionFactory.close();
- }
- }
Set的特点就是不能放置相同的物件在Set中。
也就是说,上述例子中,同一个User虽然可以对应多个emails,但是emails却不能有相同的(对同一个人而言)。
2.List映射
DDL:
- CREATE TABLE user (
- id INT(11) NOT NULL auto_increment PRIMARY KEY,
- name VARCHAR(100) NOT NULL default ''
- );
- CREATE TABLE item (
- id INT(11) NOT NULL,
- position INT(11) NOT NULL,
- name VARCHAR(100) NOT NULL default ''
- );
User.java
- package com.hb3.pack_12.model;
- import java.util.List;
- public class User {
- private Integer id;
- private String name;
- private List<String> items;
- public User() {
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public List<String> getItems() {
- return items;
- }
- public void setItems(List<String> items) {
- this.items = items;
- }
- public void addItem(String item) {
- items.add(item);
- }
- public void removeItem(String item) {
- items.remove(item);
- }
- }
User.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">
- <hibernate-mapping>
- <class name="com.hb3.pack_12.model.User" table="user">
-
- <id name="id" column="id" type="java.lang.Integer">
- <generator class="native"/>
- </id>
-
- <property name="name" column="name" type="java.lang.String"/>
-
- <list name="items" table="item">
- <key column="id"/>
- <index column="position"/>
- <element type="java.lang.String" column="name"/>
- </list>
-
- </class>
- </hibernate-mapping>
测试代码:
- package com.hb3.pack_12;
- import java.io.IOException;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import com.hb3.pack_12.model.User;
- public class BusinessService {
- public static void main(String[] args) throws IOException, SQLException {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- User user1 = new User();
- user1.setItems(new ArrayList<String>());
- user1.setName("shenbin");
- user1.addItem("DC");
- user1.addItem("CF Card");
-
- User user2 = new User();
- user2.setItems(new ArrayList<String>());
- user2.setName("chenyan");
- user2.addItem("CD");
- Transaction tx = session.beginTransaction();
- session.save(user1);
- session.save(user2);
- tx.commit();
-
- session.close();
- sessionFactory.close();
- }
- }
List是有序的结构。他在存储物品的时候还对物品所处的位置进行了记录。
3.Bag映射
DDL:
- CREATE TABLE user (
- id INT(11) NOT NULL auto_increment PRIMARY KEY,
- name VARCHAR(100) NOT NULL default ''
- );
- CREATE TABLE item (
- id INT(11) NOT NULL,
- name VARCHAR(100) NOT NULL
- );
User.java
- package com.hb3.pack_13.model;
- import java.util.List;
- public class User {
- private Integer id;
- private String name;
- private List<String> items;
- public User() {
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public List<String> getItems() {
- return items;
- }
- public void setItems(List<String> items) {
- this.items = items;
- }
- public void addItem(String item) {
- items.add(item);
- }
- public void removeItem(String item) {
- items.remove(item);
- }
- }
User.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">
- <hibernate-mapping>
- <class name="com.hb3.pack_12.model.User" table="user">
-
- <id name="id" column="id" type="java.lang.Integer">
- <generator class="native"/>
- </id>
-
- <property name="name" column="name" type="java.lang.String"/>
-
- <bag name="items" table="item">
- <key column="id"/>
- <element column="name" type="java.lang.String"/>
- </bag>
-
- </class>
- </hibernate-mapping>
测试代码:
- package com.hb3.pack_13;
- import java.io.IOException;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import com.hb3.pack_12.model.User;
- public class BusinessService {
- public static void main(String[] args) throws IOException, SQLException {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- User user1 = new User();
- user1.setItems(new ArrayList<String>());
- user1.setName("shenbin");
- user1.addItem("Java Gossip");
- user1.addItem("Java Gossip");
- user1.addItem("Caxxx A80");
-
- User user2 = new User();
- user2.setItems(new ArrayList<String>());
- user2.setName("chenyan");
- user2.addItem("Snoppy world");
-
- Transaction tx = session.beginTransaction();
- session.save(user1);
- session.save(user2);
- tx.commit();
-
- session.close();
- sessionFactory.close();
- }
- }
Bag是Hibernate自己提供的集合,他和Set的区别是它允许重复,他和List的区别是他不去管List容器中的順序。
然而,倘若要做下面的更新处理:
- Session session = sessionFactory.openSession();
- Transaction tx = session.beginTransaction();
- User user = (User) session.load(User.class, new Integer(1));
- user.removeItem("Java Gossip");
- tx.commit();
- 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能确定需要更改的那条记录从而提高效率。
新建表格:
- CREATE TABLE user (
- id INT(11) NOT NULL auto_increment PRIMARY KEY,
- name VARCHAR(100) NOT NULL default ''
- );
- CREATE TABLE item (
- cid CHAR(32) NOT NULL,
- id INT(11) NOT NULL,
- name VARCHAR(100) NOT NULL
- );
改写User.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">
- <hibernate-mapping>
- <class name="com.hb3.pack_12.model.User" table="user">
-
- <id name="id" column="id" type="java.lang.Integer">
- <generator class="native"/>
- </id>
-
- <property name="name" column="name" type="java.lang.String"/>
-
- <idbag name="items" table="item">
- <collection-id column="cid" type="java.lang.String">
- <generator class="uuid.hex"/>
- </collection-id>
- <key column="id"/>
- <element column="name" type="java.lang.String"/>
- </idbag>
-
- </class>
-
- </hibernate-mapping>
测试代码:
- package com.hb3.pack_13;
- import java.io.IOException;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import com.hb3.pack_12.model.User;
- public class BusinessService {
- public static void main(String[] args) throws IOException, SQLException {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- User user1 = new User();
- user1.setItems(new ArrayList<String>());
- user1.setName("shenbin");
- user1.addItem("Java Gossip");
- user1.addItem("Java Gossip");
- user1.addItem("Caxxx A80");
-
- User user2 = new User();
- user2.setItems(new ArrayList<String>());
- user2.setName("chenyan");
- user2.addItem("Snoppy world");
-
- Transaction tx = session.beginTransaction();
- session.save(user1);
- session.save(user2);
- tx.commit();
-
- session.close();
- session = sessionFactory.openSession();
-
-
- tx = session.beginTransaction();
- User user = (User) session.load(User.class, new Integer(1));
- user.removeItem("Java Gossip");
- tx.commit();
-
-
-
- session.close();
- sessionFactory.close();
- }
- }
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:
- CREATE TABLE user (
- id INT(11) NOT NULL auto_increment PRIMARY KEY,
- name VARCHAR(100) NOT NULL default ''
- );
- CREATE TABLE item (
- id INT(11) NOT NULL,
- name VARCHAR(100) NOT NULL,
- price decimal(10,2) NOT NULL
- );
User.java
- package com.hb3.pack_14.model;
- import java.math.BigDecimal;
- import java.util.Map;
- public class User {
- private Integer id;
- private String name;
- private Map<String, BigDecimal> items;
- public User() {
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Map<String, BigDecimal> getItems() {
- return items;
- }
- public void setItems(Map<String, BigDecimal> items) {
- this.items = items;
- }
- public void addItem(String key, BigDecimal value) {
- items.put(key, value);
- }
- public void removeItem(String key) {
- items.remove(key);
- }
- }
User.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">
- <hibernate-mapping>
- <class name="com.hb3.pack_14.model.User" table="user">
-
- <id name="id" column="id" type="java.lang.Integer">
- <generator class="native"/>
- </id>
-
- <property name="name" column="name" type="java.lang.String"/>
-
- <map name="items" table="item">
- <key column="id"/>
- <map-key column="name" type="java.lang.String"/>
- <element column="price" type="java.math.BigDecimal"/>
- </map>
-
- </class>
-
- </hibernate-mapping>
测试代码:
- package com.hb3.pack_14;
- import java.io.IOException;
- import java.math.BigDecimal;
- import java.sql.SQLException;
- import java.util.HashMap;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import com.hb3.pack_14.model.User;
- public class BusinessService {
- public static void main(String[] args) throws IOException, SQLException {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- User user1 = new User();
- user1.setItems(new HashMap<String, BigDecimal>());
- user1.setName("shenbin");
- user1.addItem("DC", new BigDecimal(100));
- user1.addItem("CF Card", new BigDecimal(80));
-
- User user2 = new User();
- user2.setItems(new HashMap<String, BigDecimal>());
- user2.setName("chenyan");
- user2.addItem("CD", new BigDecimal(180));
- Transaction tx = session.beginTransaction();
- session.save(user1);
- session.save(user2);
- tx.commit();
-
-
- session.close();
- sessionFactory.close();
- }
- }
注意:正常运行代码,需要修改hibernate.cfg.xml文件。
关于容器映射,还有如下说明。
1.內含 Component 的容器
DDL:
- CREATE TABLE user (
- id INT(11) NOT NULL auto_increment PRIMARY KEY,
- name VARCHAR(100) NOT NULL default ''
- );
- CREATE TABLE email (
- id INT(11) NOT NULL,
- address VARCHAR(100) NOT NULL
- );
MailAddress.java
- package com.hb3.pack_15.model;
- public class MailAddress {
- private String address;
- public MailAddress() {
- }
-
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- public void sendMail() {
- System.out.println("Send mail to " + address);
- }
- }
User.java
- package com.hb3.pack_15.model;
- import java.util.Set;
- public class User {
- private Integer id;
- private String name;
- private Set<MailAddress> emails;
- public User() {
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Set<MailAddress> getEmails() {
- return emails;
- }
- public void setEmails(Set<MailAddress> emails) {
- this.emails = emails;
- }
-
- public void addEmail(MailAddress mailAddress) {
- this.emails.add(mailAddress);
- }
-
- public void removeEmail(MailAddress mailAddress) {
- this.emails.remove(mailAddress);
- }
- }
User.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">
- <hibernate-mapping>
- <class name="com.hb3.pack_15.model.User" table="user">
-
- <id name="id" column="id" type="java.lang.Integer">
- <generator class="native" />
- </id>
- <property name="name" column="name" type="java.lang.String" />
-
- <set name="emails" table="email">
- <key column="id" />
- <composite-element class="com.hb3.pack_15.model.MailAddress">
- <property name="address" column="address"/>
- </composite-element>
- </set>
- </class>
- </hibernate-mapping>
测试代码:
- package com.hb3.pack_15;
- import java.io.IOException;
- import java.sql.SQLException;
- import java.util.HashSet;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- import com.hb3.pack_15.model.MailAddress;
- import com.hb3.pack_15.model.User;
- public class BusinessService {
- public static void main(String[] args) throws IOException, SQLException {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
-
- User user = new User();
- user.setName("shenbin");
-
- user.setEmails(new HashSet<MailAddress>());
- MailAddress mailAddress = new MailAddress();
- mailAddress.setAddress("bluelazysb@hotmail.com");
- user.addEmail(mailAddress);
-
- mailAddress = new MailAddress();
- mailAddress.setAddress("bluelazysb@yahoo.com.cn");
- user.addEmail(mailAddress);
-
- Transaction tx = session.beginTransaction();
- session.save(user);
- tx.commit();
-
-
- session.close();
- sessionFactory.close();
- }
- }
- Session session = sessionFactory.openSession();
-
- User user = (User) session.load(User.class, new Integer(1));
- Iterator iterator = user.getEmails().iterator();
- while(iterator.hasNext()) {
- MailAddress mailAddress = (MailAddress) iterator.next();
- mailAddress.sendMail();
- }
- 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教程