一对多的自关联,多对多的级联

一:权限菜单加载的两种方式 

1:一次性将数据表中的数据库全部加载往浏览器返回(菜单数据比较少)

2:菜单表数据量比较大,当出现浏览器卡顿的情况,那么就采用菜单逐级加载

案例:菜单对象的一对多双向自关联
   <!-- select * from t_menu where menu_id = ? -->
   <many-to-one name="superMenu" class="entity.Menu" column="super_menu_id"></many-to-one>

   <!-- select * from t_menu where super_menu_id = ? -->
   <set name="childMenus" inverse="true" lazy="true" outer-join="false" cascade="save-update">
        <key column="super_menu_id"></key>
    <one-to-many class="entity.Menu" />
   </set>

  如何将多方映射成一个有序的集合
   <!-- bag元素可以映射List集合,order-by属性还可以用来排序(asc升序|desc降序),其它和set元素的使用一样 -->
   <bag name="childMenus" inverse="true" lazy="true" outer-join="false" cascade="save-update" order-by="position asc">
        <key column="super_menu_id"></key>
    <one-to-many class="entity.Menu" />
   </bag>

 

案列:菜单对象一对多的自关联代码

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<>();

    当前节点与父节点的关系         多对一(list是有序,set是无须)	
	private List<TreeNode> children=new ArrayList<>();
	
	private TreeNode parent;
	
	//强制初始化
	private Integer initChildren;
	
	
	/*public Set<TreeNode> getChildren() {
		return children;
	}
	public void setChildren(Set<TreeNode> children) {
		this.children = children;
	}*/
	public TreeNode getParent() {
		return parent;
	}
	public List<TreeNode> getChildren() {
		return children;
	}
	public void setChildren(List<TreeNode> children) {
		this.children = children;
	}
	public void setParent(TreeNode parent) {
		this.parent = parent;
	}
	public Integer getInitChildren() {
		return initChildren;
	}
	public void setIniChildren(Integer initChildren) {
		this.initChildren = 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;
	}
	@Override
	public String toString() {
		return "TreeNode [treeNodeId=" + treeNodeId + ", treeNodeName=" + treeNodeName + ", treeNodeType="
				+ treeNodeType + ", position=" + position + ", url=" + url + ", children=" + children + "]";
	}
	
	

}
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.SessionFactoryUtil;

public class TreeNodeDao {
	public TreeNode get(TreeNode treeNode) {
		Session session = SessionFactoryUtil.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;
	}

}

 

报错: 原因直接在testdao里面直接打印tn 

 

package com.zking.five.dao;

import static org.junit.Assert.*;

import org.junit.Before;
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.setIniChildren(1);
		TreeNode tn = this.treeNodedao.get(treeNode);
		//会报错  没有初始化代理的错误
		//System.out.println(tn);
		
		//
		System.out.println(tn.getTreeNodeId()+""+tn.getTreeNodeName());
		for (TreeNode tn2 : tn.getChildren()) {
			System.out.println(tn2.getTreeNodeId()+""+tn2.getTreeNodeName());
		}
		
		/**
		 * 直接打印tn会有错误的原因
		 * 当加载一级节点的时候没有问题(一级节点是立即加载)
		 * 当加载二级节点的时候,由于设置强制加载,同样可以加载所有的二级节点。没有问题
		 * 当加载三级节点的时候,session已经关闭了,并且默认查出来的节点,默认采用的是懒加载
		 * 
		 * 权限菜单加载有两种方式
		 * 1.一次性将数据库表中的数据全部加载,往浏览器返回
		 * 2.菜单表数量比较大,当出现浏览器卡顿的情况第一种方式就不在适用。
		 * 那么久采用菜单逐级加载
		 */
	}

}

 

 

<?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.zking.five.entity.TreeNode" table="t_hibernate_sys_tree_node">
		
		<id name="treeNodeId" type="java.lang.Integer" column="tree_node_id">
			<generator class="increment" />
		</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>
		
		<!--一对多用set  -->
	<!-- 	<set  name="children" cascade="save-update" inverse="true">
		
		<key column="parent_node_id"></key>
		<one-to-many class="com.zking.five.entity.TreeNode"/>
		</set>  -->
		
		<!--position指的是数据库表的字段 让数字排序就要用list集合 映射文件的实体类改为bag -->
		<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"/>
		</bag>
		
		<many-to-one name="parent" class="com.zking.five.entity.TreeNode" column="parent_node_id"></many-to-one>
		
	</class>
</hibernate-mapping>

 

 二:多对多的级联查询

重点 理解book和category实体类映射文件中多对多关系(以及和中间表的联系)

1. 数据库的多对多
  1.1 数据库中不能直接映射多对多
      处理:创建一个桥接表(中间表),将一个多对多关系转换成两个一对多

   hibernate会自动关联桥表以及关联表查询出关联对象

      注1:数据库多表联接查询
           永远就是二个表的联接查询

           A   B   C  D
              t1   C
                   t2 D
                      t3

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

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<>();

//用于强制加载	
	private Integer initCategories=0;
	
	public Integer getInitCategories() {
		return initCategories;
	}
	public void setInitCategories(Integer initCategories) {
		this.initCategories = initCategories;
	}
	public Set<Category> getCategories() {
		return categories;
	}
	public void setCategories(Set<Category> categories) {
		this.categories = categories;
	}
	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<>();
	
	private Integer initBooks=0;
	
	public Integer getInitBooks() {
		return initBooks;
	}
	public void setInitBooks(Integer initBooks) {
		this.initBooks = initBooks;
	}
	public Set<Book> getBooks() {
		return books;
	}
	public void setBooks(Set<Book> books) {
		this.books = books;
	}
	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;
	}
	
}

 

package com.zking.five.dao;

import java.io.Serializable;

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

import com.zking.five.entity.Book;
import com.zking.two.util.SessionFactoryUtil;

public class BookDao {
	
	public Book get(Book book) {
		Session session = SessionFactoryUtil.getSession();
		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;
	}
	

}

 

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.SessionFactoryUtil;

public class CategoryDao {

	public Category get(Category category) {
		Session session = SessionFactoryUtil.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(3);
		book.setInitCategories(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 testGet1() {
		Category category=new Category();
		category.setCategoryId(1);
		category.setInitBooks(1);
		Category c = this.categoryDao.get(category);
		System.out.println(c.getCategoryName());
		for (Book b : c.getBooks()) {
			System.out.println(b.getBookName());
		}
	}
	
	

}

 

重点 理解book和category实体类映射文件中关系

<?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.zking.five.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 为中间表  name是category中的属性为set集合(一个类别多本书)-->
		<set table="t_hibernate_book_category" name="books" cascade="save-update" inverse="true">
            <!-- key column是中间表的外键 即category表的主键-->
			<key column="cid"></key>
            <!-- 多对多 中间表中的外键 即category属性book中的主键-->
			<many-to-many column="bid" class="com.zking.five.entity.Book"></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>
	<!-- session.get(Book.class,5)
			select * from t_hibernate_book where bookId =?(1)
			resultSet
			Book book=Class.forName("com.zking.five.entity.Book").newInstance();
			book.setBookId(1);
			book.setBookName(a);
			book.setPrice(50)
			
			categories为什有值?
			1:通过当前实体类的映射文件找到set标签中table属性
			select * from t_hibernate_book_category
			2.继续读取配置文件,拿到set标签中的子标签key的column属性
			   (当前类对应的表的主键在桥接表中的外键)
			   select cid from t_hibernate_book_category where bid=?(bookId=1)
			   resultSet->
			  拿到中间表的
			  
			  3.set标签many-to-many
			  com.zking.five.entity.Category
			  Category.hbm.xml
			  select * from t_hibernate_book_category
			  
			  4.利用桥接表查询出来的数据查询关联表
			  select * from t_hibernate_book_category where category_id in(1,2);
			  
			  5.最终拿到   神话   古典
			   只会得到1 2
			  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(categories)-->
		 
			  
	
			
		
		 
	<class name="com.zking.five.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>
		
		
		<!--一对多用set  -->
		<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>

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值