Hibernate 一对多自关联 多对多
今天我们要了解的是Hibernate 一对多自关联 与 多对多 首先我们先来了解一对多
一对多:
1.1 数据库中不能直接映射多对多
处理:创建一个桥接表(中间表),将一个多对多关系转换成两个一对多
注1:数据库多表联接查询
永远就是二个表的联接查询
A B C D
t1 C
t2 D
t3
注2:交叉连接
注3:外连接:left(左)/right(右)/full(左右)
主从表:连接条件不成立时,主表记录永远保留,与null匹配
A B AB
select * from A,B,AB WHERE A.aID=AB.aID and b.bid = AB.bid
where
在hibernate中,你只管查询当前表对象即可,
hibernate会自动关联桥表以及关联表查询出关联对象
Book Category Book_category
select * from Book b,Book_category bc,category where b.bid = bc.bid and bc.cid = c.cid
and bid = 2
数据库内容图片:
案列:
首先创建实体类(TreeNode.java:)和TreeNode.hbm.xml配置
TreeNode.java:
package com.lihao.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 + ", children=" + children + "]";
// }
@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.lihao.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.lihao.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.lihao.four.entity.TreeNode"/>
</set>
</class>
</hibernate-mapping>
然后别忘记在核心文件(hibernate.cfg.xml)配置:
hibernate.cfg.xml
<!-- 一对多的自动关联 -->
<mapping resource="com/lihao/four/entity/TreeNode.hbm.xml"/>
接着写dao层(TreeNodeDao:)
TreeNodeDao:
package com.lihao.four.dao;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.lihao.four.entity.TreeNode;
import com.lihao.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;
}
}
写完dao层当然就需要测试到层了就需要些一个(TreeNodeDaoTest:)类来测试
TreeNodeDaoTest:
package com.lihao.four.dao;
import org.junit.Test;
import com.lihao.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可以直接映射多对多关联关系(看作两个一对多)
多对多关系注意事项
3.1 一定要定义一个主控方
3.2 多对多删除
3.2.1 主控方直接删除
3.2.2 被控方先通过主控方解除多对多关系,再删除被控方
3.2.3 禁用级联删除
3.3 关联关系编辑,不需要直接操作桥接表,hibernate的主控方会自动维护
然后我们用案例来简单说一下多对多:
菜单表
多对多级联查询 书籍表、书籍类别表
基本步骤跟上面一样先首先创建实体类(Book.java 和 Category.java)和 book.hbm.xml 和 category.hbm.xml 配置
Book.java:
package com.lihao.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.lihao.four.entity.Book" table="t_hibernate_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)列段在中间表中的外键(bid)
many-to-many
column:对应的是上面key查出来中间表(t_hibernate_book_category)的另一个字段(cid),
当作关联表的主键(category_id)进行查询
class:上述查出来的主键对应的实体类
inverse="false"
false我自己来维护这个关联表,true代表将中间表的维护权力交给对方。
-->
<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.lihao.four.entity.Category"></many-to-many>
</set>
</class>
</hibernate-mapping>
Category.java:
package com.lihao.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 + "]";
}
}
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.lihao.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.lihao.four.entity.Book"></many-to-many>
</set>
</class>
</hibernate-mapping>
然后是别忘记在核心文件(hibernate.cfg.xml)配置:
<!-- 多对多 -->
<mapping resource="com/lihao/four/entity/Book.hbm.xml"/>
<mapping resource="com/lihao/four/entity/Category.hbm.xml"/>
然后是写dao层:
BookDao:
package com.lihao.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.lihao.four.entity.Book;
import com.lihao.four.entity.Category;
import com.lihao.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();
}
}
然后是测试BookDao类里的方法而创建BookDaoTest:
BookDaoTest:
package com.lihao.four.dao;
import org.junit.Test;
import com.lihao.four.entity.Book;
import com.lihao.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);
}
}
最后我讲解一下多对多的流程:
流程:已查询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=[{......},{.......}]}
今天就简单介绍在这里了。下期再见。