Hibernate中的多对多关系
在Hibernate中,多对多关系指的是一个实体可以与多个另一个实体实例相关联,反之亦然。为了实现这种关系,通常需要一个中间表来存储两者之间的关联信息。
多对多关系的示例代码
实体类定义
假设我们有两个实体:Student 和 Course,一个学生可以选修多门课程,一门课程也可以有多个学生。
Student类
java
package com.example.domain;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "student_course",
joinColumns = { @JoinColumn(name = "student_id") },
inverseJoinColumns = { @JoinColumn(name = "course_id") }
)
private Set<Course> courses = new HashSet<>();
public Student() {}
public Student(String name) {
this.name = name;
}
// Getters 和 Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
}
Course类
java
package com.example.domain;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@ManyToMany(mappedBy = "courses")
private Set<Student> students = new HashSet<>();
public Course() {}
public Course(String name) {
this.name = name;
}
// Getters 和 Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
Hibernate配置文件 hibernate.cfg.xml
xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接配置 -->
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/your_database</property>
<property name="hibernate.connection.username">your_username</property>
<property name="hibernate.connection.password">your_password</property>
<!-- Hibernate 属性配置 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 映射类 -->
<mapping class="com.example.domain.Student"/>
<mapping class="com.example.domain.Course"/>
</session-factory>
</hibernate-configuration>
HibernateUtil类
java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// 从配置文件创建SessionFactory
sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable ex) {
// 记录启动失败的错误
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
插入示例数据
java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class HibernateInsertData {
public static void main(String[] args) {
// 获取SessionFactory
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
// 插入示例数据
insertSampleData(sessionFactory);
// 关闭SessionFactory
sessionFactory.close();
}
private static void insertSampleData(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try {
// 创建学生
Student student1 = new Student("John Doe");
Student student2 = new Student("Jane Doe");
// 创建课程
Course course1 = new Course("Mathematics");
Course course2 = new Course("History");
// 建立多对多关系
student1.getCourses().add(course1);
student1.getCourses().add(course2);
student2.getCourses().add(course1);
student2.getCourses().add(course2);
course1.getStudents().add(student1);
course1.getStudents().add(student2);
course2.getStudents().add(student1);
course2.getStudents().add(student2);
// 保存数据
session.save(student1);
session.save(student2);
transaction.commit();
System.out.println("Inserted sample data");
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
}
查询示例数据
java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class HibernateQueryExample {
public static void main(String[] args) {
// 获取SessionFactory
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
// 查询示例数据
querySampleData(sessionFactory);
// 关闭SessionFactory
sessionFactory.close();
}
private static void querySampleData(SessionFactory sessionFactory) {
Session session = sessionFactory.openSession();
try {
// 查询所有学生
List<Student> students = session.createQuery("from Student", Student.class).list();
for (Student student : students) {
System.out.println("Student Name: " + student.getName());
for (Course course : student.getCourses()) {
System.out.println(" Enrolled in: " + course.getName());
}
}
// 查询所有课程
List<Course> courses = session.createQuery("from Course", Course.class).list();
for (Course course : courses) {
System.out.println("Course Name: " + course.getName());
for (Student student : course.getStudents()) {
System.out.println(" Student: " + student.getName());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
}
多对多关系的详细解释
-
实体类定义:
Student类和Course类通过@ManyToMany注解来定义多对多的关系。Student类中使用@JoinTable注解来定义中间表,指定了关联的学生和课程的外键。Course类中使用mappedBy属性来指定关系维护由Student类中的courses属性来负责。
-
Hibernate配置文件:
- 标准的Hibernate配置文件,用于数据库连接和映射类的配置。
-
HibernateUtil类:
- 一个实用类,用来创建和返回
SessionFactory实例。
- 一个实用类,用来创建和返回
-
插入示例数据:
- 创建
Student和Course对象,并建立多对多关系。 - 保存数据到数据库中。
- 创建
-
查询示例数据:
- 查询所有学生和他们所选修的课程,以及所有课程和选修这些课程的学生。