简介
- 创建一个桥接表(中间表),将一个多对多关系转换成两个一对多
- hibernate可以直接映射多对多关联关系(看作两个一对多)
步骤
1. 创建两个实体类表book类跟category类
public class Book implements Serializable{
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();
}
}
public class Category implements Serializable{
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 + "]";
}
}
2. 配置映射关系那就必须要用到set里中间表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.hibernate.enetiy.Book" table="t_hibernate_book">
<cache usage="read-only" region="com.hibernate.enetiy.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>
<!--
table:代表的是中间表
name:书籍类的关联属性
inverse:中间表交予对方维护
key:当前类对应的表列段在中间表(t_hibernate_book_category)中的外键bid
many-to-many:
column:对于地说上面key查出来中间表(t_hibernate_book_category)的另一个字段cid,
当作关联表的主健(category_id)进行查询
class:上述查出来的主健对应的实体类
流程:以查询book_id =1 西游记这本书为例
1、通过建模反射自动生成sql,可以拿到book_id =8这条记录的基本信息
{book_id =1,book_name=西游记,pice =50}
2、book_id =1 ->bid =1 去查询中间表t_hibernate_book_categort,
拿到了cid =1
3、cid-8,9-》t_hibernate_book_categort的category_id=1
4、拿到了当前book实例对应的category的集合
5、最终{book_id =1,book_name=西游记,pice =50}
->>>{book_id =1,book_name=西游记,price =50,categories=[categoryId=2, categoryName=神话], Category [categoryId=1, categoryName=古典]}
-->
<!-- set inverse="false"是表维护中间表的概念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.hibernate.enetiy.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 name="com.hibernate.enetiy.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 inverse="true"这是不维护这个中间表,t_hibernate_book_category -->
<set table="t_hibernate_book_category" name="books" cascade="save-update" inverse="true">
<key column="cid"></key>
<many-to-many column="bid" class="com.hibernate.enetiy.Book"></many-to-many>
</set>
</class>
</hibernate-mapping>
3.配置主映射关系连接到数据库
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 1. 数据库相关 -->
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 可以跟换方言可以打印出不同的sql语句 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 配置本地事务(No CurrentSessionContext configured!) -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 2. 调试相关 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 3.多对多的关联 -->
<mapping resource="com/hibernate/enetiy/Book.hbm.xml" />
<mapping resource="com/hibernate/enetiy/Category.hbm.xml" />
</session-factory>
</hibernate-configuration>
4.创建Book.dao方法
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();
}
}
5.执行测试增加,删除效果方法
public class BookDaoTest {
private BookDao bookDao = new BookDao();
@Test
public void testGetBook() {
Book book = new Book();
book.setBookId(1);
book.setInitCategories(1);
Book b = this.bookDao.getBook(book );
System.out.println(b.getBookName());
System.out.println(b.getCategories());
}
@Test
public void test1() {
Book book = new Book();
book.setBookName("红楼梦1");
book.setPrice(10f);
Category category = new Category();
category.setCategoryId(5);
Category c = this.bookDao.getCategory(category);
book.getCategories().add(c);
this.bookDao.addBook(book);
}
@Test
public void delbook() {
Book book = new Book();
book.setBookId(5);
this.bookDao.delBook(book);;
}
@Test
public void delcategory() {
Category category = new Category();
category.setCategoryId(1);
this.bookDao.delCategory(category);
}