1 hibernate多对多关联映射(双向User<---->Role)
映射方法:
<set name="roles" table="t_user_role">
<key column="userid"/>
<many-to-many class="com.bjsxt.hibernate.Role" column="roleid"/>
</set>
table属性值必须和单向关联中的table属性值一致
<key>中column属性值要与单向关联中的<many-to-many>标签中的column属性值一致
在<many-to-many>中的column属性值要与单向关联中<key>标签的column属性值一致
一:实体类:
- package com.tao.hibernate.many2many2;
- import java.util.Set;
- public class Role {
- private Integer id;
- private String name;
- private Set<User> users;
- public Role() {
- super();
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Set<User> getUsers() {
- return users;
- }
- public void setUsers(Set<User> users) {
- this.users = users;
- }
- }
package com.tao.hibernate.many2many2; import java.util.Set; public class Role { private Integer id; private String name; private Set<User> users; public Role() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
- package com.tao.hibernate.many2many2;
- import java.util.Set;
- public class User {
- private Integer id;
- private String name;
- private Set<Role> roles;
- public User() {
- super();
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Set<Role> getRoles() {
- return roles;
- }
- public void setRoles(Set<Role> roles) {
- this.roles = roles;
- }
- }
package com.tao.hibernate.many2many2; import java.util.Set; public class User { private Integer id; private String name; private Set<Role> roles; public User() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } }
二:映射文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping package="com.tao.hibernate.many2many2"
- auto-import="false">
- <class name="Role" table="t_role">
- <id name="id" column="id" type="integer">
- <generator class="native">
- </generator>
- </id>
- <property name="name" column="name" />
- <set name="users" table="t_user_role" order-by="userId">
- <key column="roleId" />
- <many-to-many class="User" column="userId" />
- </set>
- </class>
- </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.tao.hibernate.many2many2" auto-import="false"> <class name="Role" table="t_role"> <id name="id" column="id" type="integer"> <generator class="native"> </generator> </id> <property name="name" column="name" /> <set name="users" table="t_user_role" order-by="userId"> <key column="roleId" /> <many-to-many class="User" column="userId" /> </set> </class> </hibernate-mapping>
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping package="com.tao.hibernate.many2many2"
- auto-import="false">
- <class name="User" table="t_user">
- <id name="id" column="id" type="integer">
- <generator class="native">
- </generator>
- </id>
- <property name="name" column="name" />
- <set name="roles" table="t_user_role" cascade="all">
- <key column="userId" />
- <many-to-many class="Role" column="roleId" />
- </set>
- </class>
- </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.tao.hibernate.many2many2" auto-import="false"> <class name="User" table="t_user"> <id name="id" column="id" type="integer"> <generator class="native"> </generator> </id> <property name="name" column="name" /> <set name="roles" table="t_user_role" cascade="all"> <key column="userId" /> <many-to-many class="Role" column="roleId" /> </set> </class> </hibernate-mapping>
三:测试类:
- package com.tao.hibernate.many2many2;
- import java.util.Iterator;
- import org.hibernate.Session;
- import org.junit.Test;
- import com.tao.hibernate.HibernateUtils;
- public class TestMain {
- Session session = HibernateUtils.getFactory().openSession();
- @Test
- public void testLoad() {
- Session session = HibernateUtils.getFactory().openSession();
- Role r1 = (Role) session.load(Role.class, 1);
- System.out.println(r1.getName());
- for (Iterator<User> iter = r1.getUsers().iterator(); iter.hasNext();) {
- System.out.println(iter.next().getName());
- }
- }
- }
Student.java
- package com.entity;
- import java.io.Serializable;
- import java.util.HashSet;
- import java.util.Set;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.ManyToMany;
- import javax.persistence.Table;
- @Entity
- @Table(name = "Student")
- publicclass Student implements Serializable {
- private Integer studentid;//学生ID
- private String studentName;//学生姓名
- private Set<Teacher> teachers = new HashSet<Teacher>();//对应的教师集合
- public Student() {
- }
- public Student(String studentName) {
- this.studentName = studentName;
- }
- @Id
- @GeneratedValue
- public Integer getStudentid() {
- return studentid;
- }
- publicvoid setStudentid(Integer studentid) {
- this.studentid = studentid;
- }
- @Column(nullable = false, length = 32)
- public String getStudentName() {
- return studentName;
- }
- publicvoid setStudentName(String studentName) {
- this.studentName = studentName;
- }
- /*
- * @ManyToMany 注释表示Student是多对多关系的一边,mappedBy 属性定义了Student 为双向关系的维护端
- */
- @ManyToMany(mappedBy = "students")
- public Set<Teacher> getTeachers() {
- return teachers;
- }
- publicvoid setTeachers(Set<Teacher> teachers) {
- this.teachers = teachers;
- }
- }
package com.entity; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "Student") public class Student implements Serializable { private Integer studentid;//学生ID private String studentName;//学生姓名 private Set<Teacher> teachers = new HashSet<Teacher>();//对应的教师集合 public Student() { } public Student(String studentName) { this.studentName = studentName; } @Id @GeneratedValue public Integer getStudentid() { return studentid; } public void setStudentid(Integer studentid) { this.studentid = studentid; } @Column(nullable = false, length = 32) public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } /* * @ManyToMany 注释表示Student是多对多关系的一边,mappedBy 属性定义了Student 为双向关系的维护端 */ @ManyToMany(mappedBy = "students") public Set<Teacher> getTeachers() { return teachers; } public void setTeachers(Set<Teacher> teachers) { this.teachers = teachers; } }
多对多的关联的中间表
Teacher.java
- package com.entity;
- import java.io.Serializable;
- import java.util.HashSet;
- import java.util.Set;
- import javax.persistence.CascadeType;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.Id;
- import javax.persistence.JoinTable;
- import javax.persistence.ManyToMany;
- import javax.persistence.Table;
- import javax.persistence.JoinColumn;
- @Entity
- @Table
- publicclass Teacher implements Serializable {
- private Integer teacherid;// 教师ID
- private String teacherName;// 教师姓名
- private Set<Student> students = new HashSet<Student>();// 对应的学生集合
- public Teacher() {
- }
- public Teacher(String teacherName) {
- this.teacherName = teacherName;
- }
- @Id
- @GeneratedValue
- public Integer getTeacherid() {
- return teacherid;
- }
- publicvoid setTeacherid(Integer teacherid) {
- this.teacherid = teacherid;
- }
- @Column(nullable = false, length = 32)
- public String getTeacherName() {
- return teacherName;
- }
- publicvoid setTeacherName(String teacherName) {
- this.teacherName = teacherName;
- }
- /*
- * @ManyToMany 注释表示Teacher 是多对多关系的一端。
- * @JoinTable 描述了多对多关系的数据表关系,name属性指定中间表名称。
- * joinColumns 定义中间表与Teacher 表的外键关系,中间表Teacher_Student的Teacher_ID 列是Teacher 表的主键列对应的外键列。
- * inverseJoinColumns 属性定义了中间表与另外一端(Student)的外键关系。
- */
- @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
- @JoinTable(name = "Teacher_Student",
- joinColumns ={@JoinColumn(name = "teacher_ID", referencedColumnName = "teacherid") },
- inverseJoinColumns = { @JoinColumn(name = "student_ID", referencedColumnName = "studentid")
- })
- public Set<Student> getStudents() {
- return students;
- }
- publicvoid setStudents(Set<Student> students) {
- this.students = students;
- }
- publicvoid addStudent(Student student) {
- if (!this.students.contains(student)) {//检测在该散列表中某些键是否映射到指定值,value 查找的值。如果某些键映射到该散列表中的值为true,否则false
- this.students.add(student);
- }
- }
- publicvoid removeStudent(Student student) {
- this.students.remove(student);
- }
- }
相关推荐
二、多对多映射关系 在关系数据库中,多对多关系是指两个表之间存在多个对应关系。例如,学生可以选修多门课程,而课程也可以被多名学生选修。在Hibernate中,多对多关系通过中间表(也称为联接表或关联表)来实现,...
Hibernate是一个开源的对象关系映射(ORM)框架,它允许Java开发人员在处理数据库时使用面向对象的概念,极大地简化了数据库操作。此版本包含了Hibernate的核心库和其他相关组件,使得开发者能够将Java类与数据库表...
7. **关联映射**:包括一对一(@OneToOne)、一对多(@OneToMany)、多对一(@ManyToOne)、多对多(@ManyToMany)关系的映射,方便处理对象间的关联关系。 8. **延迟加载**:Hibernate的懒加载策略可以在需要时才...
4. `org.hibernate.boot.model`和`org.hibernate.boot.model.source`:这两个包包含了模型构建和源代码解析的相关类,用于构建实体类的元模型,是Hibernate映射的基础。 5. `org.hibernate.boot.registry`:这部分...
其改进和增强不仅提升了开发者的生产力,也降低了学习曲线,使得更多的人能够快速上手并熟练运用Hibernate进行数据库操作。 在实际应用中,开发者可以通过配置features和plugins中的内容来定制自己的开发环境,以...
本篇文章将全面探讨Hibernate的关联映射学习,包括一对一(One-to-One)、一对多(One-to-Many)、多对一(Many-to-One)以及多对多(Many-to-Many)四种关系映射。 首先,一对一关联映射(One-to-One)是两个实体...
10. 支持关联:Hibernate处理一对一、一对多、多对一和多对多关联关系。例如,使用`@OneToOne`、`@OneToMany`、`@ManyToOne`和`@ManyToMany`注解。 11. 联合主键和复合主键:在某些情况下,一个表的主键由多个字段...
包含《多对多双向关联映射》《多对一单向关联映射》《多对一双向关联映射》《一对多单向关联映射》等文档,并有图解及例子,非常适合新手学习,尤其是刚刚接触hibernate,对映射关系不清楚的。。。。
通过对一对一、一对多、多对多等映射关系的熟练掌握和灵活运用,可以有效地处理复杂的实体关系,提高开发效率和应用性能。同时,深入学习这些映射关系,不仅可以让我们更好地理解Hibernate的设计思想,还可以提升...
4. **建立映射文件或使用注解**: Hibernate使用XML映射文件(.hbm.xml)或注解来定义对象与表之间的映射关系。注解方式更简洁,可以直接在实体类上定义。 5. **操作数据**: 通过Session对象进行数据库操作。增删...
在这个“hibernate学习入门之一对多实体映射源码”教程中,我们将深入探讨如何在Hibernate中设置和管理一对多的关系。 一、Hibernate简介 Hibernate是Java开发人员用于处理数据库操作的强大工具,通过它,我们可以...
本文将深入探讨 Hibernate 中的一对一映射关系,并以"hibernate 映射关系学习入门 一对一映射Eclipse源码"为主题,详细解析其概念、配置以及实际应用。 一对一映射是Hibernate中的一种关联关系,它表示两个实体之间...
在Java的持久化框架Hibernate中,多对多(Many-to-Many)关系映射是一种常见的数据库交互模式,它用于表示两个实体之间复杂的关系。在这个场景中,一个实体可以与多个其他实体相关联,反之亦然。例如,在学生和课程...
2. 探索映射:深入理解实体类与数据库表之间的映射机制,包括一对一、一对多、多对一、多对多关系的配置。 3. 深入查询:掌握HQL和Criteria API的高级用法,如分页、排序、子查询等。 4. 事务管理:了解Hibernate的...
- Object-Relational Mapping:通过XML或注解方式定义实体类和数据库表之间的映射关系,实现对象与数据的自动转换。 3. Hibernate 5.0.7.Final新特性 - 支持JSR-349 Bean Validation 1.1:增强了实体验证功能,...
Hibernate实体关联关系映射--学习总结.pdf