1. 程式人生 > >hibernate:多對多

hibernate:多對多

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