1、建表

2、创建实体类及映射文件

Student.java类

 public class Student implements java.io.Serializable {

     // Fields

     private Integer sid;
private String sname;
private Set<Teacher> teachers=new HashSet<Teacher>(); // Constructors /** default constructor */
public Student() {
} /** full constructor */
public Student(String sname) {
this.sname = sname;
} // Property accessors public Integer getSid() {
return this.sid;
} public void setSid(Integer sid) {
this.sid = sid;
} public String getSname() {
return this.sname;
} public void setSname(String sname) {
this.sname = sname;
} public Set<Teacher> getTeachers() {
return teachers;
} public void setTeachers(Set<Teacher> teachers) {
this.teachers = teachers;
}
}

使用多对多注解应该是:

    @ManyToMany
@JoinTable(name="teacher_student",joinColumns={@JoinColumn(name="sid")},inverseJoinColumns={@JoinColumn(name="tid")})
public Set<Teacher> getTeachers() {
return teachers;
}

Teacher.java类

 public class Teacher implements java.io.Serializable {

     // Fields

     private Integer tid;
private String tname;
private Set<Student> students=new HashSet<Student>(); // Constructors /** default constructor */
public Teacher() {
} /** full constructor */
public Teacher(String tname) {
this.tname = tname;
} // Property accessors public Integer getTid() {
return this.tid;
} public void setTid(Integer tid) {
this.tid = tid;
} public String getTname() {
return this.tname;
} public void setTname(String tname) {
this.tname = tname;
} public Set<Student> getStudents() {
return students;
} public void setStudents(Set<Student> students) {
this.students = students;
}
}

被控方注解是:

    @ManyToMany(mappedBy="teachers")
public Set<Student> getStudents() {
return students;
}

Student.hbm.xml

<hibernate-mapping>
<class name="com.db.Student" table="student" catalog="mydb">
<id name="sid" type="java.lang.Integer">
<column name="sid" />
<generator class="native" />
</id>
<property name="sname" type="java.lang.String">
<column name="sname" length="32" />
</property>
<!-- 通过table属性告诉hibernate中间表,cascade指明级联操作的类型,inverse属性说明Student实体类是主控方,负责维护关系表 -->
<set name="teachers" table="teacher_student" cascade="save-update,delete" inverse="false">
<!-- 通过key属性告诉hibernate在中间表里面查询sid值相应的student记录 -->
<key>
<column name="sid" not-null="true" />
</key>
<!-- 通过column项告诉hibernate对teacher表中查找tid值相应的teacher记录 -->
<many-to-many class="com.db.Teacher" column="tid"/>
</set>
</class>
</hibernate-mapping>

Teacher.hbm.xml

<hibernate-mapping>
<class name="com.db.Teacher" table="teacher" catalog="mydb">
<id name="tid" type="java.lang.Integer">
<column name="tid" />
<generator class="native" />
</id>
<property name="tname" type="java.lang.String">
<column name="tname" length="32" />
</property>
<!-- 通过table属性告诉hibernate中间表,cascade指明级联操作的类型,inverse属性说明Teacher实体类是被控方,不负责维护关系表 ,不能触发对象和数据库的同步更新的。-->
<set name="students" table="teacher_student" inverse="true"
cascade="save-update,delete">
<key>
<column name="tid" not-null="true" />
</key>
<many-to-many class="com.db.Student" column="sid" />
</set>
</class>
</hibernate-mapping>

hibernate.cfg.xml

<hibernate-configuration>

    <session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/mydb
</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">
MyDBAccount
</property>
<property name="show_sql">true</property>
<mapping resource="com/db/Student.hbm.xml" />
<mapping resource="com/db/Teacher.hbm.xml" />
</session-factory> </hibernate-configuration>

3、建立测试用例

测试用例一:

    public static void main(String[] args) {
// TODO Auto-generated method stub Session session=HibernateSessionFactory.getSession();
Student stu1=new Student();
stu1.setSname("StudentAmy");
Teacher t1=new Teacher();
t1.setTname("TeacherSusan");
Teacher t2=new Teacher();
t2.setTname("TeacherLily");
Teacher t3=new Teacher();
t3.setTname("TeacherMaike");
Set<Teacher> teachers=new HashSet<Teacher>();
teachers.add(t1);
teachers.add(t2);
teachers.add(t3);
stu1.setTeachers(teachers);
session.save(stu1);
session.getTransaction().commit();
}

对应的SQL语句是:

Hibernate: insert into mydb.student (sname) values (?)
Hibernate: insert into mydb.teacher (tname) values (?)
Hibernate: insert into mydb.teacher (tname) values (?)
Hibernate: insert into mydb.teacher (tname) values (?)
Hibernate: insert into teacher_student (sid, tid) values (?, ?)
Hibernate: insert into teacher_student (sid, tid) values (?, ?)
Hibernate: insert into teacher_student (sid, tid) values (?, ?)

测试用例二:

    public static void main(String[] args) {
// TODO Auto-generated method stub Session session=HibernateSessionFactory.getSession();
Student stu1=new Student();
stu1.setSname("StudentJhon1");
Student stu2=new Student();
stu2.setSname("StudentLihua1");
Teacher t1=new Teacher();
t1.setTname("TeacherJay1");
t1.getStudents().add(stu1);
t1.getStudents().add(stu2);
session.beginTransaction();
session.save(t1);
session.getTransaction().commit();
} }

对应的SQL语句是:

Hibernate: insert into mydb.teacher (tname) values (?)
Hibernate: insert into mydb.student (sname) values (?)
Hibernate: insert into mydb.student (sname) values (?)

测试用例三:

    public static void main(String[] args) {
// TODO Auto-generated method stub Session session=HibernateSessionFactory.getSession();
Student stu1=new Student();
stu1.setSname("StudentJhon1");
Student stu2=new Student();
stu2.setSname("StudentLihua1");
Teacher t1=new Teacher();
t1.setTname("TeacherJay1");
t1.getStudents().add(stu1);
t1.getStudents().add(stu2);
stu2.getTeachers().add(t1);
session.beginTransaction();
session.save(t1);
session.getTransaction().commit();
} }

对应的SQL语句是:

Hibernate: insert into mydb.teacher (tname) values (?)
Hibernate: insert into mydb.student (sname) values (?)
Hibernate: insert into mydb.student (sname) values (?)
Hibernate: insert into teacher_student (sid, tid) values (?, ?)

通过测试用例发现,两个实体类都进行了级联操作,但是只有将Teacher实体对象添加到Student的teachers属性集合中时才能更新维护中间表。因为Student中的teachers集合的inverse属性是false,使得Student类成为主控方,负责维护关联关系;而Teacher中的students集合的inverse属性为true,使得Teacher类成为被控方,不会维护关联关系。

Hibernate关系映射之many-to-many的更多相关文章

  1. Hibernate学习笔记-Hibernate关系映射

    1. 初识Hibernate——关系映射 http://blog.csdn.net/laner0515/article/details/12905711 2. Hibernate 笔记8 关系映射1( ...

  2. 【SSH 基础】浅谈Hibernate关系映射(4)

    继上篇博客 多对多关联映射(单向) 多对多对象关系映射,须要增加一张新表完毕基本映射. Hibernate会自己主动生成中间表 Hibernate使用many-to-many标签来表示多对多的关联,多 ...

  3. web进修之—Hibernate 关系映射(3)

    概述 Hibernate的关系映射是Hibernate使用的难点或者是重点(别担心,不考试哦~),按照不同的分类方式可以对这些映射关系做一个分类,如: 按对象对应关系分: 一对一 多对一/一对多 多对 ...

  4. Hibernate关系映射时出现的问题

    在学习Hibernate框架的关系映射时,遇到了一个问题: INFO: HHH000422: Disabling contextual LOB creation as connection was n ...

  5. hibernate关系映射

    多对一:比如多个订单对应同一个用户,需要在订单表中添加一个用户的属性 订单类: private Integer orderId; private Date createTime; private Us ...

  6. Hibernate关系映射(注解)

    1.类级别注解 @Entity     映射实体类 @Table    映射数句库表 @Entity(name="tableName") - 必须,注解将一个类声明为一个实体bea ...

  7. Hibernate关系映射(三) 多对多

    一.使用用户User和Role实现多对多的示例 User.java,实现对Role的引用 package com.lxit.entity; import java.util.HashSet; impo ...

  8. Hibernate关系映射(三) 多对一和一对多

    一.多对一 学生Student和班级Grade实现多对一,多个学生对应一个班级. Student.java实体类,映射了班级的属性. package com.lxit.entity; import j ...

  9. Hibernate关系映射(二) 基于外键的双向一对一

    基于外键的双向一对一关联映射 需要在一端添加<one-to-one>标签,用property-ref来指定反向属性引用. 还是通过刚才用户和地址来演示双向一对一关联. 代码演示 一.实体类 ...

随机推荐

  1. SQL 模糊查询

    在进行数据库查询时,有完整查询和模糊查询之分.一般模糊查询语句如下: SELECT 字段 FROM 表 WHERE 某字段 Like 条件 其中关于条件,SQL提供了四种匹配模式:1,%:表示任意0个 ...

  2. C#基础 课堂笔记 下

           函数 1.认识函数  定义:具有独立功能,并能通过名称重复使用的代码  函数的声明位置 必须在   类   中  函数声明语法  函数声明示例  函数的调用   定义:函数调用就是使用函 ...

  3. C++ 大多数人将 cin::sync() 视为清除缓存区函数的误用

    ps:我发现有网站将我之前写的标题为:C++ 关于大多数人将cin::sync()视为清楚缓冲区函数的错误   的文章转载了,声明一下那篇文章中的内容可能存在错误,本人已删,请注意. 一百度,大多数人 ...

  4. Es6 类的关键 super、static、constructor、new.target

    ES6引入了Class(类)这个概念,作为对象的模板,通过class关键字,可以定义类.基本上,ES6的class可以看作只是一个语法糖,它的绝大部分功能,ES5都可以做到,新的class写法只是让对 ...

  5. Spring(三)--AOP【面向切面编程】、通知类型及使用、切入点表达式

    1.概念:Aspect Oriented Programming 面向切面编程 在方法的前后添加方法   2.作用:本质上来说是一种简化代码的方式      继承机制      封装方法      动 ...

  6. mvc中html导出成word下载-简单粗暴方式

    由于工作需求,需要把html简历页导出成word下载.网上搜索了很多解决方案,基本都是用一些插件,然后写法也很麻烦,需要创建模板什么的. 固定替换值  代码一大堆.但是对于我的需求来说  并没有什么用 ...

  7. MySql数据库导入导出

    1.导出整个数据库     mysqldump -u 用户名 -p 数据库名 > 存放位置     比如:     mysqldump -u root -p project > c:/a. ...

  8. sql优化策略之索引失效情况二

    详见: http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp63   接第一篇索引失效分析:http://grefr.iteye.co ...

  9. Unity相对于Cocos2d-x的比较

    1.unity:Code in C# or js       cocos:(Code in C++) 2.unity:可以让美工.动画.码农在同一个平台上各司其职(一起玩)       cocos:码 ...

  10. 全平台轻量级 Verilog 编译器 & 仿真环境

    一直苦于 modelsim 没有Mac版本,且其体量过大,在学习verilog 时不方便使用. 终于找到一组轻量级且全平台 ( Linux+Windows+macOS ) 的编译仿真工具组. Icar ...