Hibernate的关联关系(多对多)

一、简介: Hibernate的关联关系(多对多)

1. 数据库的多对多
  1.1 数据库中不能直接映射多对多
      处理:创建一个桥接表(中间表),将一个多对多关系转换成两个一对多

2. hibernate的多对多
  2.1 hibernate可以直接映射多对多关联关系(看作两个一对多) 


3. 多对多关系注意事项
  3.1 一定要定义一个主控方
  3.2 多对多删除
    3.2.1 主控方直接删除
    3.2.2 被控方先通过主控方解除多对多关系,再删除被控方
    3.2.3 禁用级联删除
  3.3 关联关系编辑,不需要直接操作桥接表,hibernate的主控方会自动维护

二、实践、操作

创建com.jiangyong.four.entity包、写实体类

2.1 Book类

package com.jiangyong.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();
	}

}

2.2 Category类

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

}

2.3 TreeNode类

package com.jiangyong.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 + ", children=" + children + "]";
	// }

	@Override
	public String toString() {
		return "TreeNode [nodeId=" + nodeId + ", nodeName=" + nodeName + ", treeNodeType=" + treeNodeType
				+ ", position=" + position + ", url=" + url + "]";
	}

}

配置各个类的xml文件

2.4 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.jiangyong.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.jiangyong.four.entity.Category"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

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

2.6 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.jiangyong.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.jiangyong.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.jiangyong.four.entity.TreeNode"/>
		</set>
	</class>
</hibernate-mapping>

三、创建src/main/resources包,配置它的映射文件

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/jt?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>

		<!-- 配置本地事务(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/jiangyong/one/entity/User.hbm.xml" />

		<!-- 4.主键生成策略 -->
		<mapping resource="com/jiangyong/two/entity/Student.hbm.xml" />
		<mapping resource="com/jiangyong/two/entity/Worker.hbm.xml" />

		<!--5、关联关系( 一对多) -->
		<mapping resource="com/jiangyong/three/entity/OrderItem.hbm.xml" />
		<mapping resource="com/jiangyong/three/entity/Order.hbm.xml" />

		<!--6、自关联关系(一对多) -->
		<mapping resource="com/jiangyong/four/entity/TreeNode.hbm.xml" />
		<!--6、自关联关系(多对多) -->
		<mapping resource="com/jiangyong/four/entity/Book.hbm.xml" />
		<mapping resource="com/jiangyong/four/entity/Category.hbm.xml" />

	</session-factory>
</hibernate-configuration>

四、创建 com.jiangyong.four.dao包、写dao方法

4.1 BookDao类

package com.jiangyong.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.jiangyong.four.entity.Book;
import com.jiangyong.four.entity.Category;
import com.jiangyong.two.util.SessionFactoryUtils;

public class BookDao {
	//新增Book
	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;
	}
	//新增Category
	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();
	}

}

4.2 BookDaoTest类

package com.jiangyong.four.dao;

import org.junit.Test;

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

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

	@Test
	public void testGetBook() {
		Book book = new Book();
		book.setBookId(8);
		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=true
	 *  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);
	}

}

4.3 TreeNodeDao类

package com.jiangyong.four.dao;

import org.hibernate.Hibernate;

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

import com.jiangyong.four.entity.TreeNode;
import com.jiangyong.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.4 TreeNodeDaoTest类

package com.jiangyong.four.dao;

import org.junit.Test;

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

}

五、总结:Hibernate关联的多对多,需要注意的是他们表与表之间的关系、还要记得配置xml文件和映射文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值