文档章节

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

乒乓狂魔
 乒乓狂魔
发布于 2015/02/07 10:24
字数 1275
阅读 56
收藏 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 (?, ?)


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

© 著作权归作者所有

共有 人打赏支持
乒乓狂魔
粉丝 1011
博文 105
码字总数 271356
作品 0
长宁
程序员
私信 提问
Java程序员从笨鸟到菜鸟之(五十四)细谈Hibernate(五)Hibernate一对多关系映射

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

长平狐
2012/11/12
457
0
Hibernate系列——总结篇(九)

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

architect刘源源
01/11
5
0
Hibernate 级联和关系维护

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

Winnie007
2015/08/28
96
0
Hibernate框架学习之注解配置关系映射

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

Single_YAM
2017/11/15
0
0
Hibernate中的cascade和inverse

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

roockee
2012/12/20
0
0

没有更多内容

加载失败,请刷新页面

加载更多

jquery通过id显示隐藏

var $div3 = $('#div3'); 显示 $div3.show(); 隐藏 $div3.hide();

yan_liu
今天
3
0
《乱世佳人》读书笔记及相关感悟3900字

《乱世佳人》读书笔记及相关感悟3900字: 之前一直听「荔枝」,后来不知怎的转向了「喜马拉雅」,一听就是三年。上班的时候听房产,买房了以后听装修,兴之所至时听旅行,分手后听亲密关系,...

原创小博客
今天
3
0
大数据教程(9.6)map端join实现

上一篇文章讲了mapreduce配合实现join,本节博主将讲述在map端的join实现; 一、需求 实现两个“表”的join操作,其中一个表数据量小,一个表很大,这种场景在实际中非常常见,比如“订单日志...

em_aaron
今天
3
0
cookie与session详解

session与cookie是什么? session与cookie属于一种会话控制技术.常用在身份识别,登录验证,数据传输等.举个例子,就像我们去超市买东西结账的时候,我们要拿出我们的会员卡才会获取优惠.这时...

士兵7
今天
3
0
十万个为什么之为什么大家都说dubbo

Dubbo是什么? 使用背景 dubbo为什么这么流行, 为什么大家都这么喜欢用dubbo; 通过了解分布式开发了解到, 为适应访问量暴增,业务拆分后, 子应用部署在多台服务器上,而多台服务器通过可以通过d...

尾生
今天
5
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部