- Domain Model:
- Relational Data Model
- The N-N association must use the join table
- Similar to the 1-n mapping, you must add a key child element for the set collection element, specifying that the foreign key of the CATEGORIES table in the Categories_items table is categoriy_id. Unlike 1-n Association mappings, when an N-N association is established, the elements in the collection use Many-to-many. The class property of the Many-to-many child element specifies that the items collection is stored in the Item object, and the column property specifies that the foreign key referenced in the items table in the Categories_items table is item_id
The example is detailed:Item.java
Package Com.atguigu.hibernate.n2n;import Java.util.hashset;import Java.util.set;public class Item {private Integer ID; Private String name;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;}}
Category.java
Package Com.atguigu.hibernate.n2n;import Java.util.hashset;import Java.util.set;public class Category {private Integer id;private String name;private set<item> items = new hashset<> ();p ublic 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<item> GetItems () {return items;} public void Setitems (set<item> items) {this.items = items;}}
Item.hbm.xml
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
Category.hbm.xml
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">