【Hibernate之关联关系四】

一对多与多对多关联关系配置
本文详细介绍了在Hibernate框架中实现一对多及多对多关联关系的方法,包括配置文件设置、实体类定义及测试代码示例。

前言

这次的关联关系是面对于其他形式的需要,

因为不好理解所以就把所讲的关联关系用图显现出来吧
第一种:一对多
在这里插入图片描述

接下来就是我们本章内容所要讲到的,就相当于一个补充。

第二种:一对多(自关联)
在这里插入图片描述

第二种:多对多
在这里插入图片描述

这就是这俩次的总内容,关联关系因为有许多种类型,所以才会有三种,
可是其实重要的还是配置文件的运用

其他的就是用来测试的

一对多(自关联)

因为自关联的类型可能有很多种,可万变不离其宗,

所以今天就准备用的是权限菜单中的表TreeNode
在这里插入图片描述

在这张表里就有我们所需要的东西

额, 就是用来测试用的啦。

所以我们用TreeNode来展示自关联。

首先因为只有一张表,这也代表着只有一个实体类,一个实体配置文件


TreeNode.java

package com.liwangwangFour.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 + "]";
	}
	

}

配置文件

配置文件可以解决90%的骚操作.
这个配置文件跟之前的没很大的区别,只不过将原本两张表的配置放到了一起。

这个实体类的属性parent对应着TreeNode表上面的parent_node_id
也表示了是多对一个的概念


<many-to-one name="parent" class="com.liwangwangFour.entity.TreeNode"
 column="parent_node_id"/>
 

children属性是一对多的概念,所以用到了《set》或者之前的《pag》
事实上也就是一个的下面有一个大集合

大集合唯一的共同点就是key

<set name="children" cascade="save-update" inverse="true">
	<key column="parent_node_id"></key>
	<one-to-many class="com.liwangwangFour.entity.TreeNode"/>
</set>
		

为了让大家参考,下面就将代码放下

<?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.liwangwangFour.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.liwangwangFour.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.liwangwangFour.entity.TreeNode"/>
		</set>
	</class>
</hibernate-mapping>

测试

public class TreeNodeDaoTest {

	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;
	}
	
	private TreeNodeDao treeNodeDao = new TreeNodeDao();


	@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());
	}

}

结果
在这里插入图片描述


多对多

就看一下实体类的,
因为是多对多,所以有三张表,我们用两个实体类,两个配置文件
book.java
在这里插入图片描述

category.java

在这里插入图片描述


配置文件

事实上也就是一个的下面有一个大集合
可是这种的是

两个表之间有一张中间表,这两个表在中间表里都有一个大集合

<set table="t_hibernate_book_category" name="categories" cascade="save-update" inverse="false">
	<key column="bid"></key>
	<many-to-many column="cid" class="com.liwangwangFour.entity.Book"></many-to-many>
</set>

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.liwangwangFour.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>
		
		<!-- 
			table : 多对多之间的中间表
			name : 书籍类所有的所有类别
			inverse : 中间表交于对方维护 false 对方维护,true 自己维护
			key : 当前类的主键在中间表里的外建名
			many-to-many :
				column : 在中间表中key相对应的主键名
				class : 对应的表的实体类
		
		 -->
		<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.liwangwangFour.entity.Book"></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.liwangwangFour.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.liwangwangFour.entity.Category"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

测试

Book.java

package com.liwangwangFour.dao;

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

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

}

Test

package com.liwangwangFour.dao;

import org.junit.Test;

import com.liwangwangFour.entity.Book;
import com.liwangwangFour.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("b");
		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=true
	 * category.hbm.xml inverse=true
	 * 只增加书籍表数据
	 * 桥接表不加数据
	 * 原因:双方都没有去维护关系
	 */
	@Test
	public void test2() {
		Book book = new Book();
		book.setBookName("c");
		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);
	}
	
	
}

总结

多对多的概念主要还是记住并且能够理解就好了,关联关系的类型有很多种
可以慢慢实验

Thanks♪(・ω・)ノ希望对大家有所帮助

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值