hibernate的自關聯和多對多(5)
阿新 • • 發佈:2018-12-17
-
資料庫的多對多 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
-
hibernate的多對多 2.1 hibernate可以直接對映多對多關聯關係(看作兩個一對多)
-
多對多關係注意事項 3.1 一定要定義一個主控方 3.2 多對多刪除 3.2.1 主控方直接刪除 3.2.2 被控方先通過主控方解除多對多關係,再刪除被控方 3.2.3 禁用級聯刪除 3.3 關聯關係編輯,不需要直接操作橋接表,hibernate的主控方會自動維護
案例: 1、自關聯查詢 選單表:
-- 一對多雙向自關聯 -- 選單表 -- t_hibernate_sys_tree_node -- t:表 -- sys:模組名縮寫(system) -- tree_noe:表名 create table t_hibernate_sys_tree_node ( tree_node_id int primary key auto_increment, -- ID tree_node_name varchar(50) not null, -- 名字 tree_node_type int not null check(tree_node_type = 1 or tree_node_type = 2), -- 節點型別:1 枝節點 2 葉節點 position int, -- 位置 parent_node_id int, -- 父節點ID url varchar(1024), -- URL foreign key(parent_node_id) references t_hibernate_sys_tree_node(tree_node_id) ); -- drop table t_hibernate_sys_tree_node -- select * from t_hibernate_sys_tree_node select * from t_hibernate_sys_tree_node; truncate table t_hibernate_sys_tree_node; insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(1,'系統管理',1, 1,null,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(2,'市場管理',1, 2,null,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(3,'字典管理',2, 3,1,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(4,'使用者管理',2, 4,1,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(5,'角色管理',2, 5,1,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(6,'許可權管理',1, 6,1,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(7,'進貨管理',2, 7,2,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(8,'銷售管理',2, 8,2,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(9,'庫存管理',2, 9,2,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(10,'使用者分配角色',2, 10,6,null); insert into t_hibernate_sys_tree_node(tree_node_id, tree_node_name, tree_node_type, position, parent_node_id, url) values(11,'角色授予使用者',2, 11,6,null);
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=0;
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 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 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.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>
<!-- <set name="children" cascade="save-update" inverse="true">
<key column="parent_node_id"></key>
<one-to-many class="com.five.entity.TreeNode"/>
</set> -->
<!-- order-by:指的是資料庫中的表字段。 position 是資料庫表中的列名,按照那個列排序 -->
<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><!--與list集合相對應,但是list用起來太麻煩, -->
<many-to-one name="parent" class="com.five.entity.TreeNode" column="parent_node_id"></many-to-one>
</class>
</hibernate-mapping>
記得配置:
<!-- 一對多的自關聯 -->
<mapping resource="com/five/entity/TreeNode.hbm.xml"/>
Dao方法:
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;
}
}
Junit:
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);//會報錯,在實際開發中不會遇到這樣的錯誤
System.out.println(tn.getTreeNodeId()+","+tn.getTreeNodeName());
for (TreeNode tn2 : tn.getChildren()) {
System.out.println(tn2.getTreeNodeId()+","+tn2.getTreeNodeName());
}
/*
* 當載入一級節點的時候沒問題
* 載入二級的時候,由於設定了強制載入,同樣可以載入所有的二級節點(子節點)
* 載入三級節點,這時session關閉了,並且預設查出來的節點,是預設採用的是懶載入,
*
* 許可權選單載入有兩種方式
* 1、一次性將資料庫表中的資料全部載入往瀏覽器返回(是用於選單較少)
* 2、選單表資料量較大,當出現瀏覽器卡頓的情況,第一種方式就不再使用。
* 那麼咱們就採用選單逐級載入。
* 1
* 1.1
* 1.2 (新增一個點選事件。然後加載出三級載入。相當於非同步)
* 1.2.1
* 1.2.2
*/
}
}
2、多對多級聯查詢 書籍表、書籍類別表 資料庫表:
-- 書本類別表
create table t_hibernate_category
(
category_id int primary key auto_increment,
category_name varchar(50) not null
);
-- 書本表
create table t_hibernate_book
(
book_id int primary key auto_increment,
book_name varchar(50) not null,
price float not null
);
-- 橋接表
-- 定義三個列,其實只要兩個列
-- 一個類別對應多本書,一本書對應多個類別
create table t_hibernate_book_category
(
bcid int primary key auto_increment,
bid int not null,
cid int not null,
foreign key(bid) references t_hibernate_book(book_id),
foreign key(cid) references t_hibernate_category(category_id)
);
insert into t_hibernate_book(book_id, book_name, price) values(1,'西遊記',50);
insert into t_hibernate_book(book_id, book_name, price) values(2,'紅樓夢',50);
insert into t_hibernate_book(book_id, book_name, price) values(3,'水滸',50);
insert into t_hibernate_book(book_id, book_name, price) values(4,'三國演義',50);
insert into t_hibernate_category(category_id, category_name) values(1,'古典');
insert into t_hibernate_category(category_id, category_name) values(2,'神話');
insert into t_hibernate_category(category_id, category_name) values(3,'歷史');
insert into t_hibernate_book_category(bid, cid) values(1,1);
insert into t_hibernate_book_category(bid, cid) values(1,2);
insert into t_hibernate_book_category(bid, cid) values(2,1);
insert into t_hibernate_book_category(bid, cid) values(3,1);
insert into t_hibernate_book_category(bid, cid) values(3,3);
insert into t_hibernate_book_category(bid, cid) values(4,1);
insert into t_hibernate_book_category(bid, cid) values(4,3);
-- 西遊記對應類別
select b.book_name, c.category_name
from t_hibernate_book b inner join t_hibernate_book_category bc on b.book_id = bc.bid inner join t_hibernate_category c on bc.cid = c.category_id
where book_id=1
-- 西遊記對應類別
select c.category_name, b.book_name
from t_hibernate_book b inner join t_hibernate_book_category bc on b.book_id = bc.bid inner join t_hibernate_category c on bc.cid = c.category_id
where category_id=1
public class Book {
private Integer bookId;
private String bookName;
private Float price;
private Set<Category> categories=new HashSet<Category>();
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;
}
}
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 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;
}
}
<?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=?(5);
resultSet->
5 a 10
Book book = Class.forName("com.five.entity.Book").newInstance();
book.setBookId(5);
book.setBookName(a);
book.setPrice(10);
categories為什麼有值?
1、當前實體類的對映檔案找到set標籤中table屬性
select * from t_hibernate_book_category
2、繼續讀取配置檔案,拿到set標籤中的子標籤的key的column屬性(當前類對應的表主鍵在橋接表中的外來鍵)
select cid from t_hibernate_book_category where bid=?(bookId=5)
resultSet->
8 5 4
9 5 5
10 5 2
只會得到2、4、5
3、set標籤->many-to-many->class
com.zking.five.entity.Category
category.hbm.xml
select * from t_hibernate_category
4、利用橋接表查詢處理的資料查詢關聯表
select * from t_hibernate_category where category_id (2,4,5)
2 神話
4 a0
5 a1
5、EntityBaseDao中的executeQuery方法,對result進行處理,最終返回
list<Category> categories = new ArrayList<>();
while(rs.next()){
Category c = Class.form("com.five.entity.Category").newInstance();
c.set....
categories.add(c);
}
6、book.setCategories(categories);
重量級框架
-->
<class table="t_hibernate_book" name="com.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>
<!-- table="t_hibernate_book_category" 橋接表 -->
<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.five.entity.Category"></many-to-many>
</set>
</class>
</hibernate-mapping>
category.hbm.xml:
<?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.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>
<!--多對多的關係,必須一個是true 一個是false 那個是true那個是false 由自己決定 至於為什麼看後面的部落格 -->
<set table="t_hibernate_book_category" name="books" cascade="save-update" inverse="true">
<key column="cid"></key>
<many-to-many column="bid" class="com.five.entity.Book"></many-to-many>
</set>
</class>
</hibernate-mapping>
配置:
<!-- 多對多的關係 -->
<mapping resource="com/zking/five/entity/category.hbm.xml"/>
<mapping resource="com/zking/five/entity/book.hbm.xml"/>
Dao:
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;
}
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;
}
Junit:
public class BookDaoTest {
private BookDao bookDao=new BookDao();
private CategoryDao categoryDao=new CategoryDao();
/**
* 通過一本書能夠查詢到多個類別
* jdbc:三表聯查
* hibernate:只需要查詢單個物件即可,它會自動關聯查詢,交給對映檔案即可。
*/
@Test
public void testGet1() {
Book book=new Book();
book.setBookId(5);
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 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());
}
}
}