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

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

一对多的自关联

映射文件TreeNode.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 name="com.MavenHibernate.four.entity.TreeNode" table="t_hibernate_sys_tree_node">
<id name="nodeId" type="java.lang.Integer" column="tree_node_id">
<generator class="increment" />
</id>
<property name="nodeName" 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> <many-to-one name="parent" class="com.MavenHidernate.four.entity.TreeNode" column="parent_node_id"/> <set name="children" cascade="save-update" inverse="true">
<key column="parent_node_id"></key>
<one-to-many class="com.MavenHidernate.four.entity.TreeNode"/>
</set>
</class>
</hibernate-mapping>

映射文件TreeNode.hbm.xml对应的实体类TreeNode.java

 package com.MavenHidernate.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<TreeNode> children = new HashSet<TreeNode>();
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<TreeNode> getChildren() {
return children;
} public void setChildren(Set<TreeNode> 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 + "]";
// } @Override
public String toString() {
return "TreeNode [nodeId=" + nodeId + ", nodeName=" + nodeName + ", treeNodeType=" + treeNodeType
+ ", position=" + position + ", url=" + url + ", parent=" + parent + ", children=" + children
+ ", initChildren=" + initChildren + "]";
} }

TreeNodeDao方法

 package com.MavenHibernate.four.dao;

 import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction; import com.MavenHibernate.two.util.SessionFactoryUtils;
import com.MavenHibernate.four.entity.TreeNode; public class TreeNodeDao {
public TreeNode load(TreeNode treeNode) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
TreeNode treenode = session.load(TreeNode.class, treeNode.getNodeId());
if(treenode != null && new Integer(1).equals(treeNode.getInitChildren())) {
Hibernate.initialize(t.getChildren());
Hibernate.initialize(t.getParent());
}
transaction.commit();
session.close();
return treenode;
}
}

junit测试TreeNodeDao

TreeNodeDaoTest

 package com.MavenHibernate.four.dao;

 import org.junit.Test;

 import com.MavenHibernate.four.entity.TreeNode;

 public class TreeNodeDaoTest {
private TreeNodeDao treeNodeDao = new TreeNodeDao(); @Test
public 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());
} }

多对多关联关系

映射文件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 name="com.MavenHibernate.four.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="t_hibernate_book_category" name="books" cascade="save-update" inverse="true">
<key column="cid"></key>
<many-to-many column="bid" class="com.MavenHibernate.four.entity.Book"></many-to-many>
</set>
</class>
</hibernate-mapping>

映射文件category.hbm.xml对应的实体类category

 package com.MavenHibernate.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 null
private Integer categoryId;
private String categoryName;
private Set<Book> books = new HashSet<Book>();
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;
}
@Override
public String toString() {
return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + "]";
} }

映射文件book.hbm.xml

  set标签
table:对应的是中间表,没有实体类的,意味着靠两张主表对应的映射文件联合管理数据
name:当前映射文件对应的实体类对应的属性
cascade:级联新增修改,说白了就是当前实体类对应的表删除能否影响到关联表的数据
inberse:中间表的数据维护的权利交给对方
key标签
column:当前表t_hibernate_book_category的主键book_id在中间表的列段bid
many-to-
many:
column:代表中间表对应的除去当前表t_hibernate_book的非主键的中间列段cid
class
:cid对应的类
 <?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.MavenHibernate.four.entity.Book" table="t_hibernate_book">
<cache usage="read-only" region="com.zking.five.entity.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标签
table:对应的是中间表,没有实体类的,意味着靠两张主表对应的映射文件联合管理数据
name:当前映射文件对应的实体类对应的属性
cascade:级联新增修改,说白了就是当前实体类对应的表删除能否影响到关联表的数据
inberse:中间表的数据维护的权利交给对方
key标签
column:当前表t_hibernate_book_category的主键book_id在中间表的列段bid
many-to-many:
column:代表中间表对应的除去当前表t_hibernate_book的非主键的中间列段cid
class:cid对应的类
-->
<set table="t_hibernate_book_category" name="categories" cascade="save-update" inverse="true">
<!-- one -->
<key column="bid"></key>
<!-- many -->
<many-to-many column="cid" class="com.MavenHibernate.four.entity.Category"></many-to-many>
</set>
</class>
</hibernate-mapping>

映射文件book.hbm.xml对应的实体类book

 package com.MavenHibernate.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 null
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 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<Category> getCategories() {
return categories;
} public void setCategories(Set<Category> categories) {
this.categories = categories;
} @Override
public 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();
} }

hibernate.cfg.xml中配置映射文件

BookDao

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

junit测试BookDao

BookDaoTest
 package com.MavenHibernate.four.dao;

 import org.junit.Test;

 import com.MavenHibernate.four.entity.Book;
import com.MavenHbernate.four.entity.Category; public class BookDaoTest {
private BookDao bookDao = new BookDao(); @Test
public 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
* 数据添加正常
* 书籍表、桥接表各新增一条数据
*/
@Test
public void test1() {
Book book = new Book();
book.setBookName("jt5555555");
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=false
* category.hbm.xml inverse=true
* 只增加书籍表数据
* 桥接表不加数据
* 原因:双方都没有去维护关系
*/
@Test
public void test2() {
Book book = new Book();
book.setBookName("T226");
book.setPrice(10);
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关联关系 (多对多)的更多相关文章

  1. hibernate关联关系(多对多)

    数据库的多对多数据库中不能直接映射多对多 处理:创建一个桥接表(中间表),将一个多对多关系转换成两个一对多 注:数据库多表联接查询 永远就是二个表的联接查询 注2:交叉连接 注3:外连接:left(左 ...

  2. hibernate关联关系的crud2

    hibernate关联关系的CRUD操作,解释都在注释里了,讲了fetchType.cascade. User类: package com.oracle.hibernate; import javax ...

  3. Hibernate中多对多的annotation的写法(中间表可以有多个字段)

    2011-07-04 6:52 一般情况下,多对多的关联关系是需要中间表的: 情况一:如果中间表仅仅是做关联用的,它里面仅有2个外键做联合主键,则使用ManyToMany(不用写中间表的Model,只 ...

  4. Hibernate 关联关系(一对多)

    Hibernate 关联关系(一对多) 1. 什么是关联(association) 1.1 关联指的是类之间的引用关系.如果类A与类B关联,那么被引用的类B将被定义为类A的属性.例如: class B ...

  5. hibernate之多对多关系

    hibernate的多对多hibernate可以直接映射多对多关联关系(看作两个一对多) 下面我们拿三张表来做实例 t_book_hb t_book_category_hb(桥接表) t_catego ...

  6. Hibernate关联关系的映射

    实体之间的关系 实体之间有三种关系 一对多:一个用户,生成多个订单,每一个订单只能属于一个用户 建表原则:在多的一方创建一个字段,作为外键,指向一的一方的主键 多对多:一个学生可以选择多门课程,一个课 ...

  7. hibernate关联关系笔记

    Hibernate关联关系笔记 单向N:1 *  有连接表:在N方使用<join>/<many-to-one>.1方无需配置与之关联的持久化类. *  没有连接表:在N方使用& ...

  8. Hibernate关联关系映射

    1.  Hibernate关联关系映射 1.1.  one to one <class name="Person"> <id name="id" ...

  9. hibernate中多对多关联

    hibernate中多对多关联 “计应134(实验班) 凌豪” 在关系数据库中有一种常见的关系即多对多关系,例如课程和学生的关系,一个学生可以选择多门课程,同时一门课程也可以被多个学生选择, 因此课程 ...

随机推荐

  1. Qt Quick 常用元素:RadioButton(单选框),CheckBox(复选框) 与 GroupBox(分组框)

    先介绍一下 ExclusiveGroup. ExclusiveGroup (互斥分组)本身是不可见元素,用于将若干个可选择元素组合在一起, 供用户选择其中的一个选项.你可以在 ExclusiveGro ...

  2. 【JSWC2019】 小X的咒语

    [JSWC2019] 小X的咒语 \(\\\) 首先这道题有三个限制: 每个点恰好两个出度和入度. 没有自环. 没有重边. 我们先定义几个变量: \(h_{i,j}\):表示有\(i\)个出度入度为\ ...

  3. 自定义httpservletrequest解析参数

    3.添加参数解析器 4.注册

  4. useEffect传入第二个参数陷入死循环

    最近新项目刚上手,就用了react的hooks,之前也看过hooks的不少文章,只是还没实战实战. 业务场景1:需要在页面一开始时得到一个接口的返回值,取调用另一个接口. 我的思路是,先设置这个接口的 ...

  5. 在Jenkins远程链接Linux系统,然后执行shell命令-亲测可用【转】

    版权声明:本文为博主原创文章,未经博主允许不得转载.部分为转载其他人的,如要使用,也请提前通知一声 https://blog.csdn.net/a136332462/article/details/7 ...

  6. Oracle学习笔记(六)

    Oralce行定位与rowid: drop table t purge; create table t as select * from dba_objects; create index idx_o ...

  7. WebUploader 上传文件 错误总结

    近日做文件上传,粗心的问题和技术不精的问题导致了很多的bug,大部分时间都是在找自己写出来的bug,近日总结一下使用 WebUploader 开启分片上传的使用方法以及注意事项 1.上传过程中,后续上 ...

  8. 在ASP.NET Web API 2中使用Owin OAuth 刷新令牌(示例代码)

    在上篇文章介绍了Web Api中使用令牌进行授权的后端实现方法,基于WebApi2和OWIN OAuth实现了获取access token,使用token访问需授权的资源信息.本文将介绍在Web Ap ...

  9. Sql 分页语句

    select * from (select *,ROW_NUMBER()over(order by [ID]) as rowindex from product ) tb  where rowinde ...

  10. vue中操作localstorage

    首先在子组件将localstorage方法进行封装 在父组件中对其进行引用 将输入的值存入到定义的searchHistory数组中,存储localstorage需要传两个参数,变量名为searchHi ...