欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

hibernate:多对多

程序员文章站 2022-04-14 21:49:46
...

1. 数据库的多对多

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

2. hibernate的多对多

2.1 hibernate可以直接映射多对多关联关系(看作两个一对多)

  1. 多对多关系注意事项
    3.1 一定要定义一个主控方
    3.2 多对多删除
    3.2.1 主控方直接删除
    3.2.2 被控方先通过主控方解除多对多关系,再删除被控方
    3.2.3 禁用级联删除
    3.3 关联关系编辑,不需要直接操作桥接表,hibernate的主控方会自动维护

案例:
自关联查询 菜单表

package com.zking.five.entity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TreeNode {
	private Integer treeNodeId;
	private String treeNodeName;
	private Integer treeNodeType;
	private Integer position;
	private String url;
	
	//当前节点与子节点的关联关系		一对多
//	private Set<TreeNode> children=new HashSet<TreeNode>();
	private List<TreeNode> children=new ArrayList<TreeNode>();
	//当前节点与父节点的关系	多对一
	private TreeNode parent;
	private Integer initChildren;
	public Integer getTreeNodeId() {
		return treeNodeId;
	}
	public void setTreeNodeId(Integer treeNodeId) {
		this.treeNodeId = treeNodeId;
	}
	public String getTreeNodeName() {
		return treeNodeName;
	}
	public void setTreeNodeName(String treeNodeName) {
		this.treeNodeName = treeNodeName;
	}
	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 List<TreeNode> getChildren() {
		return children;
	}
	public void setChildren(List<TreeNode> children) {
		this.children = children;
	}
	//	public Set<TreeNode> getChildren() {
//		return children;
//	}
//	public void setChildren(Set<TreeNode> children) {
//		this.children = children;
//	}
	public TreeNode getParent() {
		return parent;
	}
	public void setParent(TreeNode parent) {
		this.parent = parent;
	}
	public Integer getInitChildren() {
		return initChildren;
	}
	public void setInitChildren(Integer initChildren) {
		this.initChildren = initChildren;
	}
	@Override
	public String toString() {
		return "TreeNode [treeNodeId=" + treeNodeId + ", treeNodeName=" + treeNodeName + ", treeNodeType="
				+ treeNodeType + ", position=" + position + ", url=" + url + ", children=" + children + "]";
	}
	
	
}

<?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 table="t_hibernate_sys_tree_node" name="com.zking.five.entity.TreeNode">
    		<id name="treeNodeId" type="java.lang.Integer" column="tree_node_id">
    			<generator class="increment"></generator>
    		</id>
    		<property name="treeNodeName" 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>
    		
    		<!-- 
    			cascade:用来配置维护实体类之间的关系所用
    			inverse(反方,反转):关系由反方控制
    		 -->
    		<!-- <set  name="children" cascade="save-update" inverse="true">
    		填外键
    		<key column="parent_node_id"></key>
    		<one-to-many class="com.zking.five.entity.TreeNode"></one-to-many>
    		</set> -->
    		<!-- order-by指的是数据库中的表字段 -->
    		<bag order-by="position" name="children" cascade="save-update" inverse="true">
    		<!-- 填外键 -->
    		<key column="parent_node_id"></key>
    		<one-to-many class="com.zking.five.entity.TreeNode"></one-to-many>
    		</bag>
    		<many-to-one name="parent" class="com.zking.five.entity.TreeNode" column="parent_node_id"></many-to-one>
    	</class>
    </hibernate-mapping>
package com.zking.five.dao;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zking.five.entity.TreeNode;
import com.zking.two.util.SessionFactoryUtils;

public class TreeNodeDao {
	public TreeNode get(TreeNode treeNode) {
		Session session = SessionFactoryUtils.getSession();
		Transaction transaction = session.beginTransaction();
		TreeNode tn = session.get(TreeNode.class, treeNode.getTreeNodeId());
		if(tn!=null&&new Integer(1).equals(treeNode.getInitChildren())) {
			Hibernate.initialize(tn.getChildren());
		}
//		System.out.println(tn);
		transaction.commit();
		session.close();
		return tn;
		
	}
}

package com.zking.five.dao;

import static org.junit.Assert.*;

import org.junit.Test;

import com.zking.five.entity.TreeNode;

public class TreeNodeDaoTest {
	private TreeNodeDao treeNodeDao=new TreeNodeDao();

	@Test
	public void testGet() {
		TreeNode treeNode=new TreeNode();
		treeNode.setTreeNodeId(1);
		treeNode.setInitChildren(1);
		TreeNode tn = this.treeNodeDao.get(treeNode);
		System.out.println(tn.getTreeNodeId()+","+tn.getTreeNodeName());
		for (TreeNode tn2 : tn.getChildren()) {
			System.out.println(tn2.getTreeNodeId()+","+tn2.getTreeNodeName());
		}
		/**
		 * 当加载一级节点的时候没问题
		 * 当加载二级节点的时候,由于设置了强制加载,同样可以加载所有的二级节点,没问题
		 * 当加载三级节点的时候,session已经关闭了,并且默认查出来的节点是默认采用的是懒加载
		 * 
		 * 
		 * 权限菜单加载的两种方式
		 * 1、一次性将数据库表中的数据全部加载往浏览器返回(适用于菜单较少的情况)
		 * 2、菜单表数据量较大,当出现浏览器卡顿的情况,第一种方式就不再使用,那么就采用菜单逐级加载
		 * 
		 */
	}

}

多对多级联查询 书籍表、书籍类别表

package com.zking.five.entity;

import java.util.HashSet;
import java.util.Set;

public class Book {
	private Integer bookId;
	private String bookName;
	private Float price;
	private Set<Category> categories=new HashSet<Category>();
	private Integer initCategoies=0;
	
	
	public Set<Category> getCategories() {
		return categories;
	}
	public void setCategories(Set<Category> categories) {
		this.categories = categories;
	}
	public Integer getInitCategoies() {
		return initCategoies;
	}
	public void setInitCategoies(Integer initCategoies) {
		this.initCategoies = initCategoies;
	}
	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;
	}
	
	
}

package com.zking.five.entity;

import java.util.HashSet;
import java.util.Set;

public class Category {
	private Integer categoryId;
	private String categoryName;
	private Set<Book> books=new HashSet<Book>();
	private Integer initBooks=0;
	
	
	public Integer getInitBooks() {
		return initBooks;
	}
	public void setInitBooks(Integer initBooks) {
		this.initBooks = initBooks;
	}
	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;
	}
	
	
}

<?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>
   	<!-- 
   	sql语句形成讲解
   		session.get(Book.class,1);
   		select * from t_hibernate_book where bookId=?(1)
   		resultSet->
   		1	西游记	50
   		Book book=Class.forName("com.zking.five.entity.Book");
   		book.setBookId(1);
   		book.setBookName(西游记);
   		book.setPrice(50);
   		
   		categores为什么有值?
   		1、当前实体类的映射文件找到set标签的table属性
   		select * from t_hibernate_book_category
   		2、继续读取配置文件,拿到set标签中的子标签的key的column属性(column填的是当前类对应表的主键在桥接表的外键)
   		select cid from t_hibernate_book_category where bid=?(bookId=1) 
   		resultSet->
   		只会得到1,2
   		3、set标签中->many-to-many->class(找到相关联的类com.zking.five.entity.Category)
   								categoty.hbm.xml
   			select * from t_hibernate_category
   		4、利用桥接表查询出来的数据查询关联表
   		select * from t_hibernate_category where category_id in(1,2)
   		1	古典
		2	神话
   		5、EntityBaseDao中的executeQuery方法,对result进行处理,最终返回
   		List<Category> categories=new ArrayList<>();
   		while(rs.next){
   			Category c=Class.forName("com.zking.five.entity.Category").newInstance()
   			c.set...
   			
   			categories.add(c)
   		}
   		6、book.setCategories(categorise)
   		重量级框架(对sql语句极度的封装了,查单个对象可以把相关联的对象一起查出来)
   		耗性能
   		
   	 -->
    	<class table="t_hibernate_book" name="com.zking.five.entity.Book">
    		<id name="bookId" type="java.lang.Integer" column="book_id">
    			<generator class="increment"></generator><!--跨数据库的奥秘  -->
    		</id>
    		<property name="bookName" type="java.lang.String" column="book_name"></property>
    		<property name="price" type="java.lang.Float" column="price"></property>
			    		
    		<!-- 
    			cascade:用来配置维护实体类之间的关系所用
    			inverse(反方,反转):关系由反方控制
    		 -->
    		<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.zking.five.entity.Category"></many-to-many>
    		</set>
    		
    	</class>
    </hibernate-mapping>
<?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 table="t_hibernate_category" name="com.zking.five.entity.Category">
    		<id name="categoryId" type="java.lang.Integer" column="category_id">
    			<generator class="increment"></generator><!--跨数据库的奥秘  -->
    		</id>
    		<property name="categoryName" type="java.lang.String" column="category_name"></property>
    		<!-- 多对多关系的 inverse必须一个是false一个是true-->
    		<set table="t_hibernate_book_category"  name="books" cascade="save-update" inverse="true">
    		<!-- 填外键 -->
    		<key column="cid"></key>
    		<many-to-many column="bid" class="com.zking.five.entity.Book"></many-to-many>
    		</set>
    	</class>
    </hibernate-mapping>
package com.zking.five.dao;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zking.five.entity.Book;
import com.zking.five.entity.TreeNode;
import com.zking.two.util.SessionFactoryUtils;

public class BookDao {
	public Book get(Book book) {
			Session session = SessionFactoryUtils.getSession();
			Transaction transaction = session.beginTransaction();
			Book b = session.get(Book.class,book.getBookId());
			if(b!=null&&new Integer(1).equals(book.getInitCategoies())) {
				Hibernate.initialize(b.getCategories());
			}
			transaction.commit();
			session.close();
			return b;
	}
}
package com.zking.five.dao;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zking.five.entity.Book;
import com.zking.five.entity.Category;
import com.zking.two.util.SessionFactoryUtils;

public class CategoryDao {
	public Category get(Category category) {
		Session session = SessionFactoryUtils.getSession();
		Transaction transaction = session.beginTransaction();
		Category c = session.get(Category.class,category.getCategoryId());
		if(c!=null&&new Integer(1).equals(category.getInitBooks())) {
			Hibernate.initialize(c.getBooks());
		}
		transaction.commit();
		session.close();
		return c;
	}
}

package com.zking.five.dao;

import static org.junit.Assert.*;

import org.junit.Test;

import com.zking.five.entity.Book;
import com.zking.five.entity.Category;

public class BookDaoTest {
	private BookDao bookDao=new BookDao();
	private CategoryDao categoryDao=new CategoryDao();
	
	/*
	 * 通过一本书能够查到多个类别
	 * jdbc:三表联查
	 * hibernate:只需要查询单个对象即可,它会自动关联查询,交给映射文件即可
	 */

	@Test
	public void testGet() {
		Book book=new Book();
		book.setBookId(1);
		book.setInitCategoies(1);
		Book b = this.bookDao.get(book);
		System.out.println(b.getBookName());
		for (Category c : b.getCategories()) {
			System.out.println(c.getCategoryName());
			
		}
	}
	
	/**
	 * 通过一个类别查询多个书籍
	 */
	@Test
	public void testGet2() {
		Category category=new Category();
		category.setCategoryId(2);
		category.setInitBooks(1);
		Category c = this.categoryDao.get(category);
		System.out.println(c.getCategoryName());
		for (Book b : c.getBooks()) {
			System.out.println(b.getBookName());
		}
	}
}