Hibernate关联关系(多对多)

1.Hibernate关联关系(多对多)

1.1数据库中不能直接映射多对多
处理:创建一个桥接表(中间表),将一个多对多关系转换成两个一对多
1.2hibernate的多对多
hibernate可以直接映射多对多关联关系(看作两个一对多)
1.3注意事项:
1. 一定要定义一个主控方
1.4 多对多删除
1主控方直接删除
2. 被控方先通过主控方解除多对多关系,再删除被控方
3.禁用级联删除
4.关联关系编辑,不需要直接操作桥接表,hibernate的主控方会自动维护

2.案例

首先配置xml文件
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.yinyi.four.entity.Book" table="t_hibernate_book">
		<cache usage="read-only" region="com.yinyi.four.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>
		
		<!--
		table:代表的是中间表
		name:书籍类的关联属性
		inverse:中间表交于对方维护
		Key:当前类对应的表列段在中间表(t_hibernate_book_category)中的外键
		many-to-many:
				column:对应的是上面查出来的中间表(t_hibernate_book_category)的另一个字段cid,当做关联表的主键(category_id)进行查询
				class:上述查出来的主键对应的实体类
		
		
		
		流程:以查询book_id=8圣墟这本书为例
		1、通过建模反射自动生成sql,可以拿到book_id=8这条记录的基本信息{book_id=8,book_name=圣墟,price=40}
		2、book_id=8->bid=8去查询中间表t_hibernate_book_category
			拿到cid=89
		3、cid=8,9->t_hibernate_book_category的category_id=8,9
		4、拿到了当前book实例对应的category的集合
		5、最终{book_id=8,book_name=圣墟,price=40}
		->{{book_id=8,book_name=圣墟,price=40.categories=[Category [categoryId=2, categoryName=神话], Category [categoryId=1, categoryName=古典]]}}
		
		  -->
		<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.yinyi.four.entity.Category"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

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.yinyi.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.yinyi.four.entity.Book"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

TreeNode.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.yinyi.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.yinyi.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.yinyi.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/db_0611?useUnicode=true&amp;characterEncoding=UTF-8
		</property>
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- <property name="dialect">org.hibernate.dialect.MySQLDialect</property> -->
 		<property name="dialect">org.hibernate.dialect.OracleDialect</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/yinyi/one/entity/User.hbm.xml"/> 
		<!-- 讲解主键生成策略 -->
		<mapping resource="com/yinyi/two/entity/Student.hbm.xml"/> 
		<mapping resource="com/yinyi/two/entity/Worker.hbm.xml"/> 
		<!-- 一对多 -->
		<mapping resource="com/yinyi/three/OrderItem.hbm.xml"/> 
		<mapping resource="com/yinyi/three/Order.hbm.xml"/>
		<!-- 一对多的自关联 -->
		<mapping resource="com/yinyi/four/entity/TreeNode.hbm.xml"/> 
		<!-- 多对多的自关联 -->
		<mapping resource="com/yinyi/four/entity/Book.hbm.xml"/> 
		<mapping resource="com/yinyi/four/entity/Category.hbm.xml"/> 
	</session-factory>
</hibernate-configuration>

实体类:Book.java,Category.java,TreeNode.java

3.开始写dao方法

BookDao.java

package com.yinyi.four.dao;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.yinyi.four.entity.Book;
import com.yinyi.four.entity.Category;
import com.yinyi.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();
	}
	
}

TreeNodeDao.java

 package com.yinyi.four.dao;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.yinyi.four.entity.TreeNode;
import com.yinyi.two.util.SessionFactoryUtils;


public class TreeNodeDao {
	public TreeNode load(TreeNode treeNode) {
		Session session = SessionFactoryUtils.openSession();
		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;
	}
}


4.junit

BookDaoTest

package com.yinyi.four.dao;

import org.junit.Test;

import com.yinyi.four.entity.Book;
import com.yinyi.four.entity.Category;




public class BookDaoTest {
	private BookDao bookDao = new BookDao();

	@Test
	public void testGetBook() {
		Book book = new Book();
		book.setBookId(1);
		book.setInitCategories(1);
		Book b = this.bookDao.getBook(book);
		System.out.println(b.getBookName());
		System.out.println(b.getCategories());
	}
	
	/**
	 * book.hbm.xml	inverse=fasle
	 * category.hbm.xml inverse=true
	 * 数据添加正常
	 * 书籍表、桥接表各新增一条数据
	 */
	@Test
	public void test1() {
		Book book = new Book();
		book.setBookName("斗气化马");
		book.setPrice(10f);
		Category category = new Category();
		category.setCategoryId(5);
//		直接将category对象加入到新建的book中是错误的,因为此时的category是临时态的,hibernate是不会管理的
//		book.getCategories().add(category);
		Category c = this.bookDao.getCategory(category);
		
//		c.getBooks().add(book);
		book.getCategories().add(c);
		this.bookDao.addBook(book);
	}

	/**
	 * book.hbm.xml	inverse=false
	 * category.hbm.xml inverse=true
	 * 只增加书籍表数据
	 * 桥接表不加数据
	 * 原因:双方都没有去维护关系
	 */
	@Test
	public void test2() {
		Book book = new Book();
		book.setBookName("斗宗强者,恐怖如斯");
		book.setPrice(10f);
		Category category = new Category();
		category.setCategoryId(5);
		Category c = this.bookDao.getCategory(category);
		
		book.getCategories().add(c);
		this.bookDao.addBook(book);
//		c.getBooks().add(book);
	}
	
	
}

TreeNodeDaoTest.java

package com.yinyi.four.dao;

import org.junit.Test;

import com.yinyi.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());
	}

}

5.效果

在这里插入图片描述

在这里插入图片描述

6.总结:

table:代表的是中间表
name:书籍类的关联属性
inverse:中间表交于对方维护
Key:当前类对应的表列段在中间表(t_hibernate_book_category)中的外键
many-to-many:
column:对应的是上面查出来的中间表(t_hibernate_book_category)的另一个字段cid,当做关联表的主键(category_id)进行查询
class:上述查出来的主键对应的实体类

	流程:以查询book_id=8圣墟这本书为例
	1、通过建模反射自动生成sql,可以拿到book_id=8这条记录的基本信息{book_id=8,book_name=圣墟,price=40}
	2、book_id=8->bid=8去查询中间表t_hibernate_book_category
		拿到cid=8,9
	3、cid=8,9->t_hibernate_book_category的category_id=8,9
	4、拿到了当前book实例对应的category的集合
	5、最终{book_id=8,book_name=圣墟,price=40}
	->{{book_id=8,book_name=圣墟,price=40.categories=[Category [categoryId=2, categoryName=神话], Category [categoryId=1, categoryName=古典]]}}

本次的分享就到此结束,感谢您的观看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值