今天分享hibernate框架的两个关联关系

   多对多关系注意事项

  • 一定要定义一个主控方
  • 多对多删除
  1. 主控方直接删除
  2. 被控方先通过主控方解除多对多关系,再删除被控方
  3. 禁用级联删除
  • 关联关系编辑,不需要直接操作桥接表,hibernate的主控方会自动维护

重点解析:

  • 数据库的多对多

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

  • hibernate的多对多

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

一:一对多自关联

  1. 设计数据库

t_hibernate_sys_tree_node表

实体类

TreeNode类

package com.ht.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;
//0懒加载 1.强制加载(子节点) 2.强制加载用户 3.强制加载两个 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 + "]";
} }

对应实体类的配置文件

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

在核心配置文件hibernate.cfg.xml中添加实体映射文件

<!-- 一对多的自关联  -->
<mapping resource="com/ht/four/entity/TreeNode.hbm.xml" />

Dao层

去控制数据库中数据

package com.ht.four.dao;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction; import com.ht.four.entity.TreeNode;
import com.ht.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;
}
}

Junit测试类(用于测试映射关系的测试类)

TreeNodeDaoTest类

package com.ht.four.dao;

import org.junit.Test;

import com.ht.four.entity.TreeNode;

public class TreeNodeDaoTest {
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());
} }

运行结果如下图:

二:Hibernate多对多测试案例

多对多级联查询 书籍表、书籍类别表

  1. 设计数据库表

t_hibernate_book表

t_hibernate_category表

实体类

Book类

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

Category类

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

对应实体映射文件

book.hnm.xml

package com.ht.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.ht.four.entity.Book" table="t_hibernate_book">
<cache usage="read-only" region="com.ht.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:当前类对应的表列段在中间表中的外键
many-to-many:
column:对应的是上面key查出来的另一张表的主键
class:上述查出来的主键对应的实体类 流程:以查询 book_id=8这本书为例
1.通过建模反射自动生成sql,可以拿到book_id=8这条记录的基本信息
2.book_id=8 必读=8去查询中间表 t_hibernate_book_category
拿到了cid=8,9
3.cid=8,9 t_hibernate_category的category_id=8,9
4.拿到了当前book实例对应的category的集合
5.最终{book_id=8,book_name=圣墟,price=40}
-->
<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.ht.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.ht.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.ht.four.entity.Book"></many-to-many>
</set>
</class>
</hibernate-mapping>

在核心文件hibernate.cfg.xml中配置实体映射文件

<!-- 多对多实体配置文件 -->
<mapping resource="com/ht/four/entity/book.hbm.xml" />
<mapping resource="com/ht/four/entity/category.hbm.xml" />

dao层

控制数据库中的数据

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

junit测试类(给dao层测试他所写的方法是否正确)

BookDaotext类

package com.ht.four.dao;

import org.junit.Test;

import com.ht.four.entity.Book;
import com.ht.four.entity.Category; public class BookDaoTest {
private BookDao bookDao = new BookDao(); @Test
public void testGetBook() {
Book book = new Book();
book.setBookId(3);
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("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);
} }

我们来一个一个测试

首先测试查询方法可不可行

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

运行结果如下:

配置inverse属性去增加

  category.hbm.xml、book.hbm.xml中inverse属性皆为默认值true

         只增加书籍表数据
       桥接表不加数据
原因:双方都没有去维护关系

cateagory.hbm.xml

<set table="t_hibernate_book_category" name="books" cascade="save-update" inverse="true">

book.hbm.xml

<set table="t_hibernate_book_category" name="categories" cascade="save-update" inverse="true">
<!-- one -->
<key column="bid"></key>
<!-- many -->
<many-to-many column="cid" class="com.ht.four.entity.Category"></many-to-many>
</set>

谢谢观看!!!

Hibernate一对多自关联、多对多关联的更多相关文章

  1. Hibernate一对多单向(双向)关联映射

    (1).编写配置文件 Hibernate通过读写默认的XML配置文件hibernate.cfg.xml加载数据库配置信息.代码如下: <hibernate-configuration> & ...

  2. ThinkPHP5——模型关联(多对多关联)

    关联定义 多对多关联不像一对一和一对多关联,它还要多建一个中间表用来处理多对多的关联,例如: #城市 create table city ( c_id int primary key AUTO_INC ...

  3. hibernate多对多关联映射

    关联是类(类的实例)之间的关系,表示有意义和值得关注的连接. 本系列将介绍Hibernate中主要的几种关联映射 Hibernate一对一主键单向关联Hibernate一对一主键双向关联Hiberna ...

  4. Hibernate一对多、多对一关联

    一对多.多对一关联:在多方加外键 示例:Group(一方)和User(多方),一个Group可以有多个User,每个User只能属于一个Group   多对一单向关联 在User(多方)中建Group ...

  5. Java进阶知识10 Hibernate一对多_多对一双向关联(Annotation+XML实现)

    本文知识点(目录): 1.Annotation 注解版(只是测试建表)    2.XML版 的实现(只是测试建表)    3.附录(Annotation 注解版CRUD操作)[注解版有个问题:插入值时 ...

  6. (Hibernate进阶)Hibernate映射——多对多关联映射(八)

    多对多映射是现实生活中最常见的映射,也是最容易理解的映射.废话少说,直接开始. 映射原理 不论是单向关联还是双向关联都是通过第三张表,将两个表中的主键放到第三张做一个关联.用第三张表来解决可能会造成数 ...

  7. 05.Hibernate多对多关联

        前言:本文讲解使用Hibernate映射多对多关联关系,并使用多种方式映射多对多关联. 1.数据库表的多对多关系     本文根据学生信息表(tb_student)和教师信息表(tb_teac ...

  8. 03.Hibernate一对多关联

    前言:在域模型中,类与类之间最普遍的关系就是关联关系,在UML语言中关联关系是有方向的.在数据库中表与表之间也会有关联关系,本节介绍通过Hibernate映射一对多的关联关系,这是一种最普遍的关联关系 ...

  9. Mybatis 一对一、一对多、多对多关联之级联添加

    示例项目:MIPO_CRM 一.一对一关联 示例:订单与销售机会 描述:在业务员与客户的联系人的联系记录中可以生成一条销售机会,而此条销售机会可生成一条订单,两者呈一对一关联. 1.表设计 oppor ...

  10. hibernate 一对多双向关联 详解

    一.解析: 1.  一对多双向关联也就是说,在加载班级时,能够知道这个班级所有的学生. 同时,在加载学生时,也能够知道这个学生所在的班级. 2.我们知道,一对多关联映射和多对一关联映射是一样的,都是在 ...

随机推荐

  1. CF293E Close Vertice

    如果没有边数限制就是裸的淀粉质,如果有了加上一个树状数组记边数就行了. #include<stdio.h> #include<stdlib.h> #include<str ...

  2. Java核心复习—— 原子性、有序性与Happens-Before

    一. 产生并发Bug的源头 可见性 缓存导致的可见性问题 原子性 线程切换带来的原子性问题 有序性 编译优化带来的有序性问题 上面讲到了 volatile 与可见性,本章再主要讲下原子性.有序性与Ha ...

  3. 问题分析——Maven打包后发版,静态资源找不到

    一.背景 Xxl-Job-Admin(开源分布式调度中心)项目在本地运行正常,Jenkins发版到测试环境,发版成功后,打开管理页面,页面css.js找不到. 怀疑是Maven没有把静态资源打包进去导 ...

  4. 【零基础】神经网络优化之dropout和梯度校验

    一.序言 dropout和L1.L2一样是一种解决过拟合的方法,梯度检验则是一种检验“反向传播”计算是否准确的方法,这里合并简单讲述,并在文末提供完整示例代码,代码中还包含了之前L2的示例,全都是在“ ...

  5. These dependencies were not found: *!!vue-style-loader!css-loader?

    在vue中使用less首先要下载依赖:npm install less less-loader --save-dev 下载好之后就可以.vue文件中使用lang="less"和@i ...

  6. 控制 Python 工具箱中的许可行为

    def isLicensed(self): """Allow the tool to execute, only if the ArcGIS 3D Analyst 扩展模 ...

  7. Flutter移动电商实战 --(49)详细页_Stack制作底部工具栏

    一直悬浮在最下面的 Stack层叠组件.里面用Row 可以横向布局 开始 stack如果想定位就要用position去定位. 修改return返回值的这个地方 大R刷新查看效果,可以看到固定的在左下角 ...

  8. Java 中的JSON 字符串

    类库选择 Java中并没有内置JSON的解析,因此使用JSON需要借助第三方类库. 下面是几个常用的 JSON 解析类库: Gson: 谷歌开发的 JSON 库,功能十分全面. FastJson: 阿 ...

  9. [Oracle] Oracle中和MySql的limit对应的方法

    MySql很贴心,有个限制范围查询的limit函数,用起来也很方便,SQL不用嵌套.如下: select id,name,age,cdate as ctime from emp order by id ...

  10. yarn集群8088端口被攻击挖矿

    yarn集群8088端口被攻击挖矿 https://www.jianshu.com/p/a2d6b0d827ab https://blog.csdn.net/lm709409753/article/d ...