1.数据库的多对多
数据库中不能直接映射多对多
处理:创建一个桥接表(中间表),将一个多对多关系转换成两个一对多
2. hibernate的多对多
hibernate可以直接映射多对多关联关系(看作两个一对多)
3 多对多关系注意事项
一定要定义一个主控方
多对多删除
主控方直接删除
被控方先通过主控方解除多对多关系,再删除被控方
禁用级联删除
关联关系编辑,不需要直接操作桥接表,hibernate的主控方会自动维护
添加实体类及配置文件:
Book
package com.hxc.four.entity; import java.io.Serializable; import java.util.HashSet; import java.util.Set; public class Book implements Serializable{ // book_id int primary key auto_increment, // book_name varchar(50) not null, // price float not null private Integer bookId; private String bookName; private Float price; private Set<Category> categories = new HashSet<Category>(); private Integer initCategories = 0; public Integer getInitCategories() { return initCategories; } public void setInitCategories(Integer initCategories) { this.initCategories = initCategories; } public Integer getBookId() { return bookId; } public void setBookId(Integer bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public Float getPrice() { return price; } public void setPrice(Float price) { this.price = price; } public Set<Category> getCategories() { return categories; } public void setCategories(Set<Category> categories) { this.categories = categories; } @Override public String toString() { return "Book [bookId=" + bookId + ", bookName=" + bookName + ", price=" + price + "]"; } public Book(Integer bookId, String bookName) { super(); this.bookId = bookId; this.bookName = bookName; } public Book() { super(); } }
book.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.hxc.four.entity.Book" table="t_hibernate_book"> <cache usage="read-only" region="com.zking.five.entity.Book"/> <id name="bookId" type="java.lang.Integer" column="book_id"> <generator class="increment" /> </id> <property name="bookName" type="java.lang.String" column="book_name"> </property> <property name="price" type="java.lang.Float" column="price"> </property> <!-- set标签: table:是对应的中间表 没有实体类,意味着两张主表对应的映射联合管理数据 name:当前映射文件对应的实体类对应的属性 cascade:级联新增修改,说白了就是当前实体类对应的表删除是否能够影响到关联表的数据 inverse:中间表的数据维护的权力交给对方 key:标签: column:当前表t_hibernate_book的主键book_id在中间表的列段bid many-to-many: column|:代表中间表对应的除去当前表t_hibernate_book的非主键的中间表的cid class:cid对应的类 --> <set table="t_hibernate_book_category" name="categories" cascade="save-update" inverse="false"> <!-- one --> <key column="bid"></key> <!-- many --> <many-to-many column="cid" class="com.hxc.four.entity.Category"></many-to-many> </set> </class> </hibernate-mapping>
Category
package com.hxc.four.entity; import java.io.Serializable; import java.util.HashSet; import java.util.Set; public class Category implements Serializable{ // category_id int primary key auto_increment, // category_name varchar(50) not null private Integer categoryId; private String categoryName; private Set<Book> books = new HashSet<Book>(); public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public Set<Book> getBooks() { return books; } public void setBooks(Set<Book> books) { this.books = books; } @Override public String toString() { return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + "]"; } }
category.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.hxc.four.entity.Category" table="t_hibernate_category"> <id name="categoryId" type="java.lang.Integer" column="category_id"> <generator class="increment" /> </id> <property name="categoryName" type="java.lang.String" column="category_name"> </property> <set table="t_hibernate_book_category" name="books" cascade="save-update" inverse="true"> <key column="cid"></key> <many-to-many column="bid" class="com.hxc.four.entity.Book"></many-to-many> </set> </class> </hibernate-mapping>
TreeNode
package com.hxc.four.entity; import java.util.HashSet; import java.util.Set; public class TreeNode { private Integer nodeId; private String nodeName; private Integer treeNodeType; private Integer position; private String url; private TreeNode parent; private Set<TreeNode> children = new HashSet<TreeNode>(); private Integer initChildren = 0; public Integer getNodeId() { return nodeId; } public void setNodeId(Integer nodeId) { this.nodeId = nodeId; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public Integer getTreeNodeType() { return treeNodeType; } public void setTreeNodeType(Integer treeNodeType) { this.treeNodeType = treeNodeType; } public Integer getPosition() { return position; } public void setPosition(Integer position) { this.position = position; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public TreeNode getParent() { return parent; } public void setParent(TreeNode parent) { this.parent = parent; } public Set<TreeNode> getChildren() { return children; } public void setChildren(Set<TreeNode> children) { this.children = children; } public Integer getInitChildren() { return initChildren; } public void setInitChildren(Integer initChildren) { this.initChildren = initChildren; } @Override public String toString() { return "TreeNode [nodeId=" + nodeId + ", nodeName=" + nodeName + ", treeNodeType=" + treeNodeType + ", position=" + position + ", url=" + url + ", initChildren=" + initChildren + "]"; } // @Override // public String toString() { // return "TreeNode [nodeId=" + nodeId + ", nodeName=" + nodeName + ", treeNodeType=" + treeNodeType // + ", position=" + position + ", url=" + url + ", children=" + children + "]"; // } }
treeNode.hxm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.hxc.four.entity.TreeNode" table="t_hibernate_sys_tree_node"> <id name="nodeId" type="java.lang.Integer" column="tree_node_id"> <generator class="increment" /> </id> <property name="nodeName" type="java.lang.String" column="tree_node_name"> </property> <property name="treeNodeType" type="java.lang.Integer" column="tree_node_type"> </property> <property name="position" type="java.lang.Integer" column="position"> </property> <property name="url" type="java.lang.String" column="url"> </property> <many-to-one name="parent" class="com.hxc.four.entity.TreeNode" column="parent_node_id"/> <set name="children" cascade="save-update" inverse="true"> <key column="parent_node_id"></key> <one-to-many class="com.hxc.four.entity.TreeNode"/> </set> </class> </hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 1. 数据库相关 --> <property name="connection.username">root</property> <property name="connection.password">123</property> <property name="connection.url">jdbc:mysql://localhost:3306/mytable?useUnicode=true&characterEncoding=UTF-8 </property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 配置本地事务(No CurrentSessionContext configured!) --> <property name="hibernate.current_session_context_class">thread</property> <!-- 2. 调试相关 --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- 3. 添加实体映射文件 --> <mapping resource="com/hxc/one/entity/user.hbm.xml" /> <!-- 主键生成策略 --> <mapping resource="com/hxc/two/entity/Student.hbm.xml"/> <mapping resource="com/hxc/two/entity/Worker.hbm.xml"/> <!-- 一对多关联关系 --> <mapping resource="com/hxc/three/entity/Order.hbm.xml"/> <mapping resource="com/hxc/three/entity/OrderItem.hbm.xml"/> <!-- 一对多自关联 --> <mapping resource="com/hxc/four/entity/TreeNode.hbm.xml"/> <!-- 多对多关联 --> <mapping resource="com/hxc/four/entity/Book.hbm.xml"/> <mapping resource="com/hxc/four/entity/Category.hbm.xml"/> </session-factory> </hibernate-configuration>
BookDao
package com.hxc.four.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.query.Query; import com.hxc.four.entity.Book; import com.hxc.four.entity.Category; import com.hxc.two.util.SessionFactoryUtils; public class BookDao{ public Integer addBook(Book book) { Session session = SessionFactoryUtils.openSession(); Transaction transaction = session.beginTransaction(); Integer bid = (Integer) session.save(book); transaction.commit(); session.close(); return bid; } public Integer addCategory(Category category) { Session session = SessionFactoryUtils.openSession(); Transaction transaction = session.beginTransaction(); Integer cid = (Integer) session.save(category); transaction.commit(); session.close(); return cid; } public Category getCategory(Category category) { Session session = SessionFactoryUtils.openSession(); Transaction transaction = session.beginTransaction(); Category c = session.get(Category.class, category.getCategoryId()); transaction.commit(); session.close(); return c; } public Book getBook(Book book) { Session session = SessionFactoryUtils.openSession(); Transaction transaction = session.beginTransaction(); Book b = session.get(Book.class, book.getBookId()); if (b != null && new Integer(1).equals(book.getInitCategories())) { Hibernate.initialize(b.getCategories()); } transaction.commit(); session.close(); return b; } public void delBook(Book book) { Session session = SessionFactoryUtils.openSession(); Transaction transaction = session.beginTransaction(); session.delete(book); transaction.commit(); session.close(); } public void delCategory(Category category) { Session session = SessionFactoryUtils.openSession(); Transaction transaction = session.beginTransaction(); Category c = session.get(Category.class, category.getCategoryId()); if(c!=null) { for (Book b : c.getBooks()) { // 通过在被控方通过主控方来解除关联关系,最后被控方再做删除 b.getCategories().remove(c); } } session.delete(c); transaction.commit(); session.close(); } }
BookDao:
package com.hxc.four.dao; import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import com.hxc.four.entity.TreeNode; import com.hxc.two.util.SessionFactoryUtils; public class TreeNodeDao { public TreeNode load(TreeNode treeNode) { Session session = SessionFactoryUtils.openSession(); System.out.println(session); Transaction transaction = session.beginTransaction(); TreeNode t = session.load(TreeNode.class, treeNode.getNodeId()); if(t != null && new Integer(1).equals(treeNode.getInitChildren())) { Hibernate.initialize(t.getChildren()); Hibernate.initialize(t.getParent()); } transaction.commit(); session.close(); return t; } }
BookDaoTest
package com.hxc.four.dao; import org.junit.Test; import com.hxc.four.entity.TreeNode; public class TreeNodeDaoTest { private TreeNodeDao treeNodeDao = new TreeNodeDao(); // @Before // public void setUp() throws Exception { // } // // @After // public void tearDown() throws Exception { // } @Test public void testLoad() { TreeNode treeNode = new TreeNode(); treeNode.setNodeId(6); treeNode.setInitChildren(1); TreeNode t = this.treeNodeDao.load(treeNode); System.out.println(t); System.out.println(t.getParent()); System.out.println(t.getChildren()); } }
运行BookDaoTest:
![](https://img2018.cnblogs.com/blog/1691488/201908/1691488-20190807200122496-1865887189.png)
![](https://img2018.cnblogs.com/blog/1691488/201908/1691488-20190807200134134-1567484250.png)
运行 BookDaoTest中的getBook: