文档章节

hibernate系列(三)多对多的关联关系

乒乓狂魔
 乒乓狂魔
发布于 2015/02/07 10:24
字数 1275
阅读 54
收藏 1
以Teacher和Student为例,他们之间是多对多的关系。
手动创建的数据库的三张表为,teacher、student、teacher_student。分别如下:

CREATE TABLE `teacher` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `teacher_student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `teacher_id` int(11) DEFAULT NULL,
  `student_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Teacher类如下:
public class Teacher {

	private Long id;
	private String name;
	private Set<Student> students;
//省略get、set方法
}

Teacher类对应的映射文件Teacher.hbm.xml:
<hibernate-mapping>
	<class name="com.ligang.domain.Teacher" table="teacher">
		<id name="id" column="id" type="long">
			<generator class="identity"/>
		</id>
		<property name="name" column="name" type="string"/>
		<set name="students" table="teacher_student">
			<key column="teacher_id"></key>
			<many-to-many class="com.ligang.domain.Student" column="student_id"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

其中set标签的name指的是Teacher类的students属性,table指的是该属性要关联到哪张表。内部的key标签的column指的是该Teacher类所属的表的主键id作为teacher_student的外键teacher_id值。<many-tomany>标签指的是Student类所属的student表的主键作为teacher_student表的student_id值。
Stusent类如下:

public class Student {

	private Long id;
	private String name;
	private Set<Teacher> teachers;
//省略get、set方法
}

Student类对应的映射文件Student.hbm.xml如下:
<hibernate-mapping>
	<class name="com.ligang.domain.Student" table="student">
		<id name="id" column="id" type="long">
			<generator class="identity"/>
		</id>
		<property name="name" column="name" type="string"/>
		<set name="teachers" table="teacher_student"  inverse="true">
			<key column="student_id"></key>
			<many-to-many class="com.ligang.domain.Teacher" column="teacher_id"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

其中的set映射关系同上。
然后就来看下增添方法:

@Test
	public void testAddTeacher1(){
		Session session=hibernateDao.getSession();
		Transaction tx=session.beginTransaction();
		
		Teacher t=new Teacher();
		t.setName("teacher4");
		
		Student s1=new Student();
		s1.setName("assa");
		
		Student s2=new Student();
		s2.setName("sdfvdv");
		
		Set<Student> students=new HashSet<Student>();
		students.add(s1);
		students.add(s2);
		
		t.setStudents(students);
		
		session.save(s1);
		session.save(s2);
		session.save(t);
		
		tx.commit();
		session.close();
	}

三个save,三个insert语句,同时,由于t.setStudents(students),所以teacher会去维护teacher_student关系表,所以又会增添两条insert语句,sql如下:
Hibernate: insert into hibernate.student (name) values (?)
Hibernate: insert into hibernate.student (name) values (?)
Hibernate: insert into hibernate.teacher (name) values (?)
Hibernate: insert into hibernate.teacher_student (teacher_id, student_id) values (?, ?)
Hibernate: insert into hibernate.teacher_student (teacher_id, student_id) values (?, ?)

如果增添改为如下状态:
@Test
	public void testAddTeacher(){
		Session session=hibernateDao.getSession();
		Transaction tx=session.beginTransaction();
		
		Teacher t=new Teacher();
		t.setName("teacher4");
		
		Student s1=new Student();
		s1.setName("assa");
		
		Student s2=new Student();
		s2.setName("sdfvdv");
		
		Set<Student> students=new HashSet<Student>();
		Set<Teacher> teachers=new HashSet<Teacher>();
		students.add(s1);
		students.add(s2);
		teachers.add(t);
		
		t.setStudents(students);
		s1.setTeachers(teachers);
		s2.setTeachers(teachers);
		
		session.save(s1);
		session.save(s2);
		session.save(t);
		
		tx.commit();
		session.close();
	}

此时,不仅建立起了t.setStudents(students)关系,同时s1.setTeachers(teachers);s2.setTeachers(teachers);也建立了关系,所以最终事务提交的时候,teacher、student都会去维护teacher_student表,造成了4个insert语句,造成了重复。如下:
Hibernate: insert into hibernate.student (name) values (?)
Hibernate: insert into hibernate.student (name) values (?)
Hibernate: insert into hibernate.teacher (name) values (?)
Hibernate: insert into hibernate.teacher_student (student_id, teacher_id) values (?, ?)
Hibernate: insert into hibernate.teacher_student (student_id, teacher_id) values (?, ?)
Hibernate: insert into hibernate.teacher_student (teacher_id, student_id) values (?, ?)
Hibernate: insert into hibernate.teacher_student (teacher_id, student_id) values (?, ?)

为了避免这一现象,就需要某一方放弃维护teacher_student表的权限。如student放弃维护这一关系,使用inverse="true",如下:
<hibernate-mapping>
	<class name="com.ligang.domain.Student" table="student">
		<id name="id" column="id" type="long">
			<generator class="identity"/>
		</id>
		<property name="name" column="name" type="string"/>
		<set name="teachers" table="teacher_student" inverse="true">
			<key column="student_id"></key>
			<many-to-many class="com.ligang.domain.Teacher" column="teacher_id"></many-to-many>
		</set>
	</class>
</hibernate-mapping>

此时再按照上述方法增添就只有teacher去维护teacher_student表了,不会造成重复。

再看下多对多关联关系的查询:

@Test
	public void getTeacher(){
		Session session=hibernateDao.getSession();
		Transaction tx=session.beginTransaction();
		
		Teacher t=(Teacher) session.get(Teacher.class,3L);
		System.out.println(t.getName());
		System.out.println(t.getStudents().size());
		
		tx.commit();
		session.close();
	}

这里同样存在这查询策略问题,此时Teacher类的映射文件对应的set标签的lazy属性有三个值,一个true、false、extra。默认为true,即实行延迟加载的策略,用到Student时才回去加载它,如下sql:
Hibernate: select teacher0_.id as id1_3_0_, teacher0_.name as name2_3_0_ from hibernate.teacher teacher0_ where teacher0_.id=?
teacher2
Hibernate: select students0_.teacher_id as teacher_1_3_0_, students0_.student_id as student_2_4_0_, student1_.id as id1_2_1_, student1_.name as name2_2_1_ from hibernate.teacher_student students0_ inner join hibernate.student student1_ on students0_.student_id=student1_.id where students0_.teacher_id=?
2

若设置为false,则表示在加载Teacher时立即去加载相关的Student,如下sql:
Hibernate: select teacher0_.id as id1_3_0_, teacher0_.name as name2_3_0_ from hibernate.teacher teacher0_ where teacher0_.id=?
Hibernate: select students0_.teacher_id as teacher_1_3_0_, students0_.student_id as student_2_4_0_, student1_.id as id1_2_1_, student1_.name as name2_2_1_ from hibernate.teacher_student students0_ inner join hibernate.student student1_ on students0_.student_id=student1_.id where students0_.teacher_id=?
teacher2
2

若设置为extra,则会更加智能化一些,即上述t.getStudents().size()并没有去访问Student的实际内容,仅仅是想获取数量,所以sql语句如下:
Hibernate: select teacher0_.id as id1_3_0_, teacher0_.name as name2_3_0_ from hibernate.teacher teacher0_ where teacher0_.id=?
teacher2
Hibernate: select count(student_id) from hibernate.teacher_student where teacher_id =?
2

再看下更新Teacher:
@Test
	public void updateTeacher(){
		Session session=hibernateDao.getSession();
		Transaction tx=session.beginTransaction();
		
		Teacher t=(Teacher) session.get(Teacher.class,6L);
		
		Student s1=new Student();
		s1.setName("assa");
		
		Student s2=new Student();
		s2.setName("sdfvdv");
		
		Set<Student> students=new HashSet<Student>();
		students.add(s1);
		students.add(s2);
		
		t.setStudents(students);
		
		session.save(s1);
		session.save(s2);
		
		tx.commit();
		session.close();
	}

更新的时候,会先删除之前的teacher_student表中的相关记录,然后再新增新的记录,如下sql:
Hibernate: select teacher0_.id as id1_3_0_, teacher0_.name as name2_3_0_ from hibernate.teacher teacher0_ where teacher0_.id=?
Hibernate: insert into hibernate.student (name) values (?)
Hibernate: insert into hibernate.student (name) values (?)
Hibernate: delete from hibernate.teacher_student where teacher_id=?
Hibernate: insert into hibernate.teacher_student (teacher_id, student_id) values (?, ?)
Hibernate: insert into hibernate.teacher_student (teacher_id, student_id) values (?, ?)


若想转载请注明出处
作者:乒乓狂魔

© 著作权归作者所有

共有 人打赏支持
乒乓狂魔
粉丝 994
博文 105
码字总数 271356
作品 0
长宁
程序员
Hibernate系列——总结篇(九)

概念 Hibernate是一个对象关系映射框架,当然从分层的角度看,我们也说它是数据持久层的框架。 我们从上一句话可以看出Hibernate的核心:面向对象、关系映射以及数据持久化。前面两个概念很容...

architect刘源源
01/11
5
0
Java程序员从笨鸟到菜鸟之(五十四)细谈Hibernate(五)Hibernate一对多关系映射

前几篇系列博客: 细谈Hibernate(一)hibernate基本概念和体系结构 细谈Hibernate(二)开发第一个hibernate基本详解 细谈Hibernate(三)Hibernate常用API详解及源码分析 细谈Hibernate(四...

长平狐
2012/11/12
425
0
Hibernate框架学习之注解配置关系映射

上篇文章我们通过注解对映射了单个实体类,但是具体项目中往往实体类之间又是相互关联的,本篇文章就是从实体类之间存在的不同关联角度,具体学习下如何映射他们之间的关联,主要涉及内容如下...

Single_YAM
2017/11/15
0
0
Hibernate 级联和关系维护

1、Hibernate中的级联操作: 在Hibernate中,针对持久化实体的配置文件中有Cascade这样一个属性,就是级联,也就是说在操作当前实体时,针对当前实体的操作会影响到相应配置的关联实体,比如...

Winnie007
2015/08/28
96
0
Hibernate中的cascade和inverse

这两个属性都用于一多对或者多对多的关系中。而inverse特别是用于双向关系,在单向关系中我们并不需要。 Cascade代表是否执行级联操作,Inverse代表是否由己方维护关系。 Cascade: Cascade属...

roockee
2012/12/20
0
0

没有更多内容

加载失败,请刷新页面

加载更多

分布式框架spring-session实现session一致性使用问题

前言:项目中使用到spring-session来缓存用户信息,保证服务之间session一致性,但是获取session信息为什么不能再服务层获取? 一、spring-session实现session一致性方式 用户每一次请求都会...

WALK_MAN
15分钟前
1
0
C++ yield()与sleep_for()

C++11 标准库提供了yield()和sleep_for()两个方法。 (1)std::this_thread::yield(): 线程调用该方法时,主动让出CPU,并且不参与CPU的本次调度,从而让其他线程有机会运行。在后续的调度周...

yepanl
23分钟前
0
0
Java并发编程实战(chapter_3)(线程池ThreadPoolExecutor源码分析)

这个系列一直没再写,很多原因,中间经历了换工作,熟悉项目,熟悉新团队等等一系列的事情。并发课题对于Java来说是一个又重要又难的一大块,除非气定神闲、精力满满,否则我本身是不敢随便写...

心中的理想乡
33分钟前
15
0
shell学习之获取用户的输入命令read

在运行脚本的时候,命令行参数是可以传入参数,还有就是在脚本运行过程中需要用户输入参数,比如你想要在脚本运行时问个问题,并等待运行脚本的人来回答。bash shell为此提 供了read命令。 ...

woshixin
59分钟前
1
0
区块链技术中的那些能商用的企业级应用

WEPOWER是一家立陶宛初创企业,旨在改变可再生电力项目的付费方式。WePower公司创始人Nick Martyniuk表示,政府统一收购价的存在推动了全球风能与太阳能市场的发展。因此,他的公司希望帮助那...

问题终结者
今天
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部