引子:
表与表之间的关系,如果说,一本书有多个对应类别,我们一般是创建外键,但一个类别对应多本书的话,我们要想描述这种关系,就要用到中间表。
针对这种情况,hibernate是如何处理的呢?
目录:
- 自关联查询
- 多对多级联查询
- inverse属性值
首先,本节主要依据的是书籍表(t_hibernate_book)、书籍类别表(t_hibernate_category)和中间表(t_hibernate_book_category),进行代码剖析与映射配置
自关联查询
自关联查询主要是在上节代码上进行的操作与思路解析
TreeNode:
package com.ly.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 children = new HashSet();
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 + "]";
}
}
其中private Integer initChildren = 0; // 0 懒加载 1 强制加载(子节点) 2 强制加载用户 3 强制加载两个
(两个表之间)
是我们需要了解的关于自关联查询的一个内容,至于多个表,我们也可以在TreeNodeDao里面进行代码操作,0或者1或者2或者3是我们表的排列数组得出来的结果,最大数为结果。
以两个表为例子,我们在TreeNodeDao里面:
package com.ly.four.dao;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.ly.four.entity.TreeNode;
import com.ly.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;
}
}
维护后主要代码操作:
if(t != null && new Integer(0).equals(treeNode.getInitChildren())) {
Hibernate.initialize(t.getChildren());
}
if(t != null && new Integer(1).equals(treeNode.getInitChildren())) {
Hibernate.initialize(t.getParent());
}
if(t != null && new Integer(3).equals(treeNode.getInitChildren())) {
Hibernate.initialize(t.getChildren());
Hibernate.initialize(t.getParent());
}
这里我们主要理解即可,实际上由于表绝对不可能只有几个,由于维护过于麻烦而不被人们青睐
多对多级联查询
hibernate多对多级联查询我们主要以配置,分析思路为主。
大家可以在代码中体会,当然代码中也有注释。
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.ly.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>
<!--
table代表的是中间表
name:书籍类的关键属性
inverse:中间表交于对方维护
key:当前类对应的表列段在中间表的外键bid
many-to-many:
column:对应的是上面key查出来的另一个字段,当做关联表的主键进行查询
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_category的category_id=8,9
4,拿到了当前book实例对应的category的集合
5,最终{book_id=8,book_name=肾虚,price=40}
{book_id=8,book_name=肾虚,price=40,categories=[[categoryId=3, 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.ly.four.entity.Category"></many-to-many>
</set>
</class>
</hibernate-mapping>
这里面我们需要注意
<set>
<key/>
<many-to-many/>
</set>
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.ly.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.ly.four.entity.Book"></many-to-many>
</set>
</class>
</hibernate-mapping>
在我们理解上面代码中提到的流程,我们也就对多对多关系有了更好的理解。
小结:
table代表的是中间表
name:书籍类的关键属性
inverse:中间表交于对方维护
key:当前类对应的表列段在中间表的外键bid
many-to-many:
column:对应的是上面key查出来的另一个字段,当做关联表的主键进行查询
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_category的category_id=8,9
4,拿到了当前book实例对应的category的集合
5,最终{book_id=8,book_name=肾虚,price=40}
{book_id=8,book_name=肾虚,price=40,categories=[[categoryId=3, categoryName=历史], Category [categoryId=1, categoryName=古典]}
inverse属性值
我们可以看出,无论是在book.hbm.xml还是在category.hbm.xml中都有inverse这个属性值,
这也是本节的一个重要知识点。
inverse我们可以认作为是为了维护中间表,指的是两个主表,(第二人称对方)
如果维护中间表的是book表,那么我们在book表中新增一条数据,中间表也会增加一条相关的数据,反之亦然。
具体操作结合代码:
BookDao:
package com.ly.four.dao;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.ly.four.entity.Book;
import com.ly.four.entity.Category;
import com.ly.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();
}
}
BookDaoTest
package com.ly.four.dao;
import org.junit.Test;
import com.ly.four.entity.Book;
import com.ly.four.entity.Category;
public class BookDaoTest {
private BookDao bookDao = new BookDao();
@Test
public void testGetBook() {
Book book = new Book();
book.setBookId(4);
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);
}
}
这里面我们说明了条件,根据我们inverse属性值前言可以分析得出
inverse小结:
这里指的都是inverse在两个配置文件的属性值:
1、book:false category:true 这里我们可以得知category方不愿维护,book方维护
2、book:true category:false这里我们可以得知book方不愿维护,category方维护
3、book:true category:true 这里是错误的
4、book:false category:false 也是错误的
如果我们按照上面1,2 两种方法来操作,我们在book方增加数据,中间表也增加了,反之亦然。