hibernate 自关联以及多对多:
项目大体图:
数据库表:
提供TreeNodeDao.java
package com.pyc.four.dao;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.pyc.first.util.SessionFactoryUtils;
import com.pyc.four.entity.TreeNode;
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;
}
}
提供TreeNodeDaoTest.java
package com.pyc.four.dao;
import org.junit.Test;
import com.pyc.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());
}
}
提供TreeNode.java
package com.pyc.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 + "]";
}
}
提供TreeNode.hgm.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.pyc.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.pyc.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.pyc.four.entity.TreeNode"/>
</set>
</class>
</hibernate-mapping>
下一步配置hibernate.cfg.xml
Dao方法TreeNodeDao.java
package com.pyc.four.dao;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.pyc.first.util.SessionFactoryUtils;
import com.pyc.four.entity.TreeNode;
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;
}
}
测试类TreeNodeDaoTest.java
package com.pyc.four.dao;
import org.junit.Test;
import com.pyc.four.entity.TreeNode;
public class TreeNodeDaoTest {
private TreeNodeDao treeNodeDao = new TreeNodeDao();
// @Before
// public void setUp() throws Exception {
// }
//
// @After
// public void tearDown() throws Exception {
// }
/**
* 注意:
* 1.这个在Vue的后台要用
* 2.它只能加载出直系亲属(父节点跟子节点)
*/
@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());
}
}
测试结果:
2. hibernate的多对多
2.1 hibernate可以直接映射多对多关联关系(看作两个一对多)
多对多关系注意事项
2.1 一定要定义一个主控方
2.2 多对多删除
2.2.1 主控方直接删除
2.2.2 被控方先通过主控方解除多对多关系,再删除被控方
2.2.3 禁用级联删除
2.3 关联关系编辑,不需要直接操作桥接表,hibernate的主控方会自动维护
案例:
自关联查询 菜单表
多对多级联查询 书籍表、书籍类别表
Book.java
package com.pyc.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.pyc.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:中间表的数据维护交给那个实体类来控制:inverse的字面意思是反方,
默认inverse=true,那也就意味着,默认由对方来控制中间表数据的维护
key标签
colum:当前映射类Book对应的表t_hibernate_book的主键,在中间表的外键
many-to-many标签:
colum:当前映射类关联属性对应的类的主键,在中间表的外键
class:当前映射类关联属性对应的类的全路径名
-->
<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.pyc.four.entity.Category"></many-to-many>
</set>
</class>
</hibernate-mapping>
Category.java
package com.pyc.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.pyc.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.pyc.four.entity.Book"></many-to-many>
</set>
</class>
</hibernate-mapping>
BookDao.java
package com.pyc.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.pyc.first.util.SessionFactoryUtils;
import com.pyc.four.entity.Book;
import com.pyc.four.entity.Category;
import antlr.StringUtils;
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();
}
}
// /*
// * hql讲解用到(需要继承BaseDao)
// */
// /**
// * 没有使用BaseDao之前的代码
// * @param book
// * @param pageBean
// * @return
// */
// public List<Book> list(Book book, PageBean pageBean) {
// Session session = SessionFactoryUtils.openSession();
// Transaction transaction = session.beginTransaction();
// String hql = "from Book where 1 = 1";
//
// if (StringUtils.isNotBlank(book.getBookName())) {
// hql += " and bookName like :bookName";
// }
//
// Query query = session.createQuery(hql);
//
// if (StringUtils.isNotBlank(book.getBookName())) {
// query.setParameter("bookName", book.getBookName());
// }
//
// if (pageBean != null && pageBean.isPagination()) {
// query.setFirstResult(pageBean.getStartIndex());
// query.setMaxResults(pageBean.getRows());
// }
// List<Book> list = query.list();
// transaction.commit();
// session.close();
// return list;
//
// }
//
// /**
// * 使用BaseDao之后的代码
// * @param book
// * @param pageBean
// * @return
// */
// public List<Book> list2(Book book, PageBean pageBean) {
// Session session = SessionFactoryUtils.openSession();
// Transaction transaction = session.beginTransaction();
// String hql = "from Book where 1 = 1";
// Map<String, Object> map = new HashMap<String, Object>();
//
// if (StringUtils.isNotBlank(book.getBookName())) {
// hql += " and bookName like :bookName";
// map.put("bookName", book.getBookName());
// }
// List list = super.executeQuery(session, hql, map, pageBean);
// transaction.commit();
// session.close();
// return list;
// }
//
// /**
// * 使用原生SQL
// * @param book
// * @param pageBean
// * @return
// */
// public List list3(Book book, PageBean pageBean) {
String sql = "select b.*,o.* from t_hibernate_book b,t_hibernate_Order o";
// String sql = "select * from t_hibernate_book";
// Session session = SessionFactoryUtils.openSession();
// Transaction transaction = session.beginTransaction();
// List list = session.createSQLQuery(sql).list();
// transaction.commit();
// session.close();
// return list;
// }
//}
BookDaoTest.java
package com.pyc.four.dao;
import org.junit.Test;
import com.pyc.four.entity.Book;
import com.pyc.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("T237冲冲冲2");
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);
}
}
添加hibernate.cfg.xml配置
测试BookDaoTest中的testGetBook方法:
测试BookDaoTest中的test1():
关于inverse问题:
场景一:
将category.hbm.xml配置中的 inverse=“true” 改成 inverse=“false”
将book.hbm.xml配置中的 inverse=“false” 改成 inverse=“true”
重新测试test1。
结果 t_hibernate_book插入数据成功,而 t_hibernate_category 插入数据失败
//book不能维护,所以说中间表的数据不添加
**//哪怕说一正一反,如果你维护的对象不对,那么这个中间表的数据依然不会添加 **
//首先我们是填一正一反 一个为true 一个为 false 其次false的一方才能去维护中间表的关系
//现在我们代码上是想让book去维护这个关系但是我们配置上false给的是category,所以说中间表不加数据
场景二:
将category.hbm.xml配置中的 inverse=“false” 改成 inverse=“true”
测试test2()
只增加书籍表数据 中间表添加失败
双方都没有去维护关系
**问题所在:**中间表的数据没人进行维护。
hibernate中多对多的底层查询原理
<!--
hibernate中多对多的查询原理:
1.建模得到sessionfactory工厂
2.sessionfactory包含两个多对多的关系映射文件,那么就可以通过流加载那两个映射文件
这里以com/wangcong/four/entity/Category.hbm.xml,加载完后可以对应再次建模
3.可以拿到com.wangcong.four.entity.Category以及表t_hibernate_category
通过t_hibernate_category以及下列的column列段可以多态生成sql语句
select category_id,category_name from t_hibernate_category where category_id=?(5)
最终查出 5 a1这条数据
Category c= Class.forName("com.wangcong.four.entity.Category")
Filed categoryNameFiled= c.getClass().getDecafiedld("categoryName");
categoryNameFiled.setAccessable(true);
categoryNameFiled.set(c,"a1");
同理:
categoryIdFiled.set(c,5);
那么也就意味着当前c实例中所有属性值以及赋值完毕
4.同样对此文件建模com/wangcong/four/entity/Category.hbm.xml,可以得到
中间表t_hibernate_book_category,以及关联属性的全路径名com.wangcong.four.entity.Book
自然形成sql语句
select cid,bid from t_hibernate_book_category where cid=?(5)
查询出来的结果:
5 17 5
6 20 5
7 21 5
8 22 5
9 24 5
11 26 5
String sql=select * from t_hibernate_book where book_id in(17,20,....)
List<book> books= BaseDao.executeQuery(sql,Book.class,null)
BaseDao.executeQuery(sql,Class clz,pagebean)
5.c.setBooks(books)
-->