数据库中不能直接映射多对多
如何处理:创建一个桥接表(中间表),将一个多对多关系转换成两个一对多
注1:数据库多表联接查询
永远就是二个表的联接查询
注2:交叉连接
注3:外连接:left(左)/right(右)/full(左右)
主从表:连接条件不成立时,主表记录永远保留,与null匹配
bernate_sys_tree_node表结构
**封装类TreeNode **
package com.zxp.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;
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 getChildren() {
return children;
}
public void setChildren(Set 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
配置核心文件
Dao方法
package com.zxp.four.dao;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.zxp.four.entity.TreeNode;
import com.zxp.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;
}
}
测试方法
package com.zxp.four.dao;
import org.junit.Test;
import com.zxp.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();
// NodeId6 --》权限管理
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());
}
}
实体类Book:
package com.zxp.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 categories = new HashSet();
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 getCategories() {
return categories;
}
public void setCategories(Set 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.zxp.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 books = new HashSet();
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 getBooks() {
return books;
}
public void setBooks(Set books) {
this.books = books;
}
@Override
public String toString() {
return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + "]";
}
}
映射文件book.hbm.xml
映射文件category.hbm.xml
dao方法
package com.zxp.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.zxp.four.entity.Category;
import com.zxp.four.entity.Book;
import com.zxp.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();
}
}
测试类
package com.zxp.four.dao;
import org.junit.Test;
import com.zxp.four.entity.Book;
import com.zxp.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("zxp");
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);
}
}
测试testGetBook
成功得到了 书名和其对应的类别后,接着测试test1和test2,并且改变inverse的值
通过测试上面的方法,改变配置文件中inverse的值,我们可以得知:
1.book维护方
book.hbm.xml inverse=fasle
category.hbm.xml inverse=true
数据添加正常 因为这里book是负责维护的一方
书籍表、中间表各新增一条数据
2.category维护
book.hbm.xml inverse=true
category.hbm.xml inverse=false
书籍表数据添加正常 中间表添加失败
因为这里category是负责维护的一方,但是实际应该是book进行维护
3.双方都不维护
book.hbm.xml inverse=true
category.hbm.xml inverse=true
只增加书籍表数据 中间表添加失败
原因:双方都没有去维护关系
底层原理
hibernate中多对多的底层原理:
1、建模得到sessionfactory工厂
2、sessionfactory中包含两个多对多关系映射文件,
那么就可以通过流加载那两个映射文件,
这里以 "com/zxp/four/entity/category.hbm.xml"为例,
加载完后可以对其建模
3、可以拿到"com/zxp/four/entity/category.hbm.xml" 以及表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/zxp/four/entity/category.hbm.xml")
Field categoryNameField = c.getClass().getDecafiedld("categoryName")
categoryNameField.setAccessable(true);打开权限
categoryNameField.set(c,"a1");
同理可以设置属性:
categoryNameField.set(c,5);
那也就意味着当前c实例中所有属性值已经赋值完毕
4、同样对此文件com/zxp/four/entity/category.hbm.xml建模可以得到
中间表 t_hibernate_book_category
以及关联属性的全路径名com.zxp.four.entity.Book
自然形成一个sql语句:
select bid,cid from t_hibernate_book_category where cid=?(假设 5)
查询结果:5 17 5
6 20 5
……
select * from t_hibernate_book where book_id in (17,20...)
BaseDao.executeQuery(sql,Class clz,pagebean)
List books = BaseDao.executeQuery(sql,Book.class,null)
5、给关联属性赋值
c.setBooks(books)