hibernate之关联关系(多对多)

hibernate 自关联以及多对多:

自关联:用于左侧树的加载

提供项目大体图片:
在这里插入图片描述
开始撸代码
提供TreeNodeDao.java

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

提供TreeNodeDaoTest.java

package com.wangcong.four.dao;import org.junit.Test;import com.wangcong.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.它只能加载出直系亲属(父子点和子节点)*    既爷爷和孙子加载不出来(最多只支持三级)*/ @Testpublic 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.wangcong.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 + "]";
//	}@Overridepublic String toString() {return "TreeNode [nodeId=" + nodeId + ", nodeName=" + nodeName + ", treeNodeType=" + treeNodeType+ ", position=" + position + ", url=" + url + "]";}}

提供TreeNode.hgm.xml





以及在hibernate.cfg,xml的配置:

   

测试结果:
在这里插入图片描述
多对多:
提供项目大体图片:
在这里插入图片描述
撸代码开始:
Book.java

package com.wangcong.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 nullprivate 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;}@Overridepublic 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





Category.java

package com.wangcong.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 nullprivate 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;}@Overridepublic String toString() {return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + "]";}}

category.hbm.xml





BookDao.java

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

BookDaoTest.java

package com.wangcong.four.dao;import org.junit.Test;import com.wangcong.four.entity.Book;
import com.wangcong.four.entity.Category;public class BookDaoTest {private BookDao bookDao = new BookDao();@Testpublic 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* 数据添加正常* 书籍表、桥接表各新增一条数据*/@Testpublic void test1() {Book book = new Book();book.setBookName("only老K自传");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* 只增加书籍表数据* 桥接表不加数据* 原因:双方都没有去维护关系*/@Testpublic 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方法:

结果如下图:
在这里插入图片描述
测试test1
在这里插入图片描述
在这里插入图片描述
结果成功。

关于inverse问题:

场景一:
将category.hbm.xml配置中的 inverse=“true” 改成 inverse="false"

将book.hbm.xml配置中的 inverse=“false” 改成 inverse="true"

重新测试test1

结果 t_hibernate_book插入数据成功,而 t_hibernate_category 插入数据失败
在这里插入图片描述
在这里插入图片描述
问题所在: 维护对象不对(只能false方维护中间表的数据)
更改代码之后Category来维护中间表的数据,但是在方法中是book在维护,导致维护失败
在这里插入图片描述
场景二:

将category.hbm.xml配置中的 inverse=“false” 改成 inverse="true"

测试test2
在这里插入图片描述
中间表依旧没数据。

**问题所在:**中间表的数据没人进行维护。

hibernate中多对多的底层查询原理


存在问题:hibernate 做一次查询要用到三次查询,性能很低


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部