hibrenate多对多关联

数据库与hebrenate的多对多

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

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

        A   B   C  D
           t1   C  D
                t2 D
                   t3
    

    注2:交叉连接
    注3:外连接:left(左)/right(右)/full(左右)
    主从表:连接条件不成立时,主表记录永远保留,与null匹配

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

多对多关系注意事项

1.一定要定义一个主控方
2. 多对多删除
2.1 主控方直接删除
2.2 被控方先通过主控方解除多对多关系,再删除被控方
2.3 禁用级联删除
3. 关联关系编辑,不需要直接操作桥接表,hibernate的主控方会自动维护

代码演示:

实体类:
book

package com.zhoujun.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Book implements Serializable {
		private Integer bookId;
		private String bookName;
		private Float price;
		Set<Category> categories=new HashSet<Category>();
		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 + ", categories="
					+ categories + "]";
		}		
}

book实体类映射:

<?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.zhoujun.entity.Book" table="t_book_hb">
		 <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 name="price" type="java.lang.Float" column="price"/>
		 <!-- 多对多映射 -->
		 <!-- 
		 	name:一方包含多方的属性对象名,指向多方
		 	cascade:级联操作 sava-update/none/delete/all=delete+save-update
		 	inverse:是否是主控方,false表示对方不是主控方,
		 	true表示对方是主控方,由对方更新(维护)中间表
		 	table:表示中间表名称
		  -->
		 <set 	name="categorys"
		 		cascade="save-update"
		 	  	inverse="false"
		 	  	table="t_book_category_hb">
		 	  <!-- column:指向己方在中间表的外键字段 -->
		 	<key column="bid"></key>
		 	<!-- 
		 		class:对方实体类路径
		 		column:对方在中间表的外键
		 	 -->
		 	<many-to-many class="com.zhoujun.entity.Category"
		 					column="cid">
		 	</many-to-many>
		 </set>
	</class>
</hibernate-mapping>

Category

package com.zhoujun.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Category implements Serializable {
	private Integer categoryId;
	private String caregoryName;
	Set<Book> categories=new HashSet<Book>();
	public Integer getCategoryId() {
		return categoryId;
	}
	public void setCategoryId(Integer categoryId) {
		this.categoryId = categoryId;
	}
	public String getCaregoryName() {
		return caregoryName;
	}
	public void setCaregoryName(String caregoryName) {
		this.caregoryName = caregoryName;
	}
	public Set<Book> getCategories() {
		return categories;
	}
	public void setCategories(Set<Book> categories) {
		this.categories = categories;
	}
	@Override
	public String toString() {
		return "Category [categoryId=" + categoryId + ", caregoryName=" + caregoryName + ", categories=" + categories
				+ "]";
	}	
}

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.zhoujun.entity.Category" table="t_category_hb">
		 <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"/>
		 <!-- 多对多映射关系 -->
		 <set 	name="books"
		 		cascade="save-update"
		 	  	inverse="true"
		 	  	table="t_book_category_hb">
		 	<key column="cid"></key>
		 	<many-to-many class="com.zhoujun.entity.Book"
		 					column="bid">
		 	</many-to-many>
		 </set>
	</class>
</hibernate-mapping>

dao类:
bookdao

package com.zhoujun.dao;

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

import com.zhoujun.entity.Book;
import com.zhoujun.util.SessionFactoryUtils;
public class BookDao {
	public void addBook(Book book) {
		Session session=SessionFactoryUtils.openSession();
		Transaction ts=session.beginTransaction();
		session.save(book);
		ts.commit();
		SessionFactoryUtils.closeSession();
	}
	
}

Categorydao:

package com.zhoujun.dao;

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

import com.zhoujun.entity.Category;
import com.zhoujun.util.SessionFactoryUtils;

public class CategoryDao {

	public Category getCategoryById(Category category) {
		Session session=SessionFactoryUtils.openSession();
		Transaction ts=session.beginTransaction();
		Category c=session.get(Category.class,category.getCategoryId());
		ts.commit();
		SessionFactoryUtils.closeSession();
		return c;
	}
}

util工具类:

package com.zhoujun.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactoryUtils {

	private static final String 
			HIBERNATE_CONFIG_FILE="hibernate.cfg.xml";
	
	private static ThreadLocal<Session> threadLocal=
			new ThreadLocal<Session>();
	
	//创建数据库的会话工厂
	private static SessionFactory sessionFactory;
	
	//读取hibernate核心配置
	private static Configuration configuration;
	
	static {
		try {
			configuration=new Configuration();
			configuration.configure(HIBERNATE_CONFIG_FILE);
			//创建Session会话工厂
			sessionFactory=configuration.buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Session openSession() {
		Session session = threadLocal.get();
		if(null==session) {
			session=sessionFactory.openSession();
			threadLocal.set(session);
		}
		return session;
	}
	
	public static void closeSession() {
		Session session = threadLocal.get();
		if(null!=session) {
			if(session.isOpen())
				session.close();
			threadLocal.set(null);
		}
	}
	
	public static void main(String[] args) {
		Session session = SessionFactoryUtils.openSession();
		System.out.println("Session状态:"+session.isOpen());
		System.out.println("Session会话已打开");
		SessionFactoryUtils.closeSession();
		System.out.println("Session会话已关闭");
	}
}

测试类:
bookdao测试

package com.zhoujun.dao;


import com.zhoujun.entity.Book;
import com.zhoujun.entity.Category;

import junit.framework.TestCase;


public class BookDaoTest extends TestCase {

	BookDao bookdao=new BookDao();
	Book book=null;
	
	protected void setUp() throws Exception {
		book=new Book();
		
	}

	public void testAddBook() {
		book.setBookName("ma劈");
		book.setPrice(100f);
		
		Category category=new Category();
		category.setCaregoryName("药店");
		Category category1=new Category();
		category1.setCaregoryName("吊毛");
		
		book.getCategories().add(category);
		book.getCategories().add(category1);
		category.getCategories().add(book);
		category.getCategories().add(book);
//		category.getBooks().add(book);
//		category1.getBooks().add(book);
		
		bookdao.addBook(book);
	}

}

Category测试

package com.zhoujun.dao;

import com.zhoujun.entity.Book;
import com.zhoujun.entity.Category;

import junit.framework.TestCase;

public class CategoryDaoTest extends TestCase {

	CategoryDao categorydao = null;
	BookDao bookdao=new BookDao();

	protected void setUp() throws Exception {
		categorydao = new CategoryDao();
	}

	public void testGetCategoryById() {
		Book book = new Book();
		book.setBookName("是的");
		book.setPrice(240f);

		Category category = new Category();
		category.setCategoryId(2);
		Category c=categorydao.getCategoryById(category);
		
		book.getCategories().add(c);
		bookdao.addBook(book);
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值