(学习记录,错误不足之处,请您耐心指正^_^)
hibernate映射-多对多关联关系
n-n关联必须使用连接表才能完成,
一、代码示例:
{类文件↓}
Category.class
1 package com.zit.hibernate.n2n; 2 3 import java.util.HashSet; 4 import java.util.Set; 5 6 public class Category { 7 8 private Integer id; 9 private String name; 10 11 private Set<Item> items = new HashSet<>(); 12 13 public Integer getId() { 14 return id; 15 } 16 public void setId(Integer id) { 17 this.id = id; 18 } 19 public String getName() { 20 return name; 21 } 22 public void setName(String name) { 23 this.name = name; 24 } 25 public Set<Item> getItems() { 26 return items; 27 } 28 public void setItems(Set<Item> items) { 29 this.items = items; 30 } 31 32 }
Item.class
1 package com.zit.hibernate.n2n; 2 3 public class Item { 4 5 private Integer id; 6 private String name; 7 8 public Integer getId() { 9 return id; 10 } 11 public void setId(Integer id) { 12 this.id = id; 13 } 14 public String getName() { 15 return name; 16 } 17 public void setName(String name) { 18 this.name = name; 19 } 20 21 }
(单向n-n)
{映射文件↓}
Item.hbm.xml
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 <!-- Generated 2015-12-25 13:55:35 by Hibernate Tools 3.4.0.CR1 --> 5 <hibernate-mapping package="com.zit.hibernate.n2n"> 6 <class name="Item" table="ITEMS"> 7 <id name="id" type="java.lang.Integer"> 8 <column name="ID" /> 9 <generator class="native" /> 10 </id> 11 <property name="name" type="java.lang.String"> 12 <column name="NAME" /> 13 </property> 14 </class> 15 </hibernate-mapping>
Category.hbm.xml
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 <!-- Generated 2015-12-25 13:55:35 by Hibernate Tools 3.4.0.CR1 --> 5 <hibernate-mapping package="com.zit.hibernate.n2n"> 6 <class name="Category" table="CATEGORIES"> 7 <id name="id" type="java.lang.Integer"> 8 <column name="ID" /> 9 <generator class="native" /> 10 </id> 11 <property name="name" type="java.lang.String"> 12 <column name="NAME" /> 13 </property> 14 <set name="items" table="CATEGORIES_ITEMS"> 15 <key> 16 <column name="C_ID" /> 17 </key> 18 <many-to-many class="Item" column="I_ID"></many-to-many> 19 </set> 20 </class> 21 </hibernate-mapping>
在Category.hbm.xml中,
1 <set name="items" table="CATEGORIES_ITEMS"> 2 <key> 3 <column name="C_ID" /> 4 </key> 5 <many-to-many class="Item" column="I_ID"></many-to-many> 6 </set>
这里的table指定中间表的名字,key 子元素,指定该中间表中参照CATEGORIES表的外键为C_ID.
使用many-to-many时,class属性指定items集合中存放的是Item对象,column指定中间表中参照ITEMS表的外键
名为 I_ID。
(中间表未指定主键,那么两个属性联合起来作为主键。)
二、使用注意:
1.保存记录时,由于两个表并没有直接的联系,所以,先后保存哪一个数据,并没有直接的影响。但save记录时,需要同时操作中间表,所以,会相应的多出insert语句。
2.查询时,有懒加载,在查询set<Item>的size时,会将 中间表与ITEMS表进行内连接查询。
(学习记录,错误不足之处,请您耐心指正^_^)