java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Hibernate 多对多

Hibernate处理多对多关系的实现示例

作者:辞暮尔尔-烟火年年

本文介绍了Hibernate中实现多对多关系的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Hibernate中的多对多关系

在Hibernate中,多对多关系指的是一个实体可以与多个另一个实体实例相关联,反之亦然。为了实现这种关系,通常需要一个中间表来存储两者之间的关联信息。

多对多关系的示例代码

实体类定义

假设我们有两个实体:StudentCourse,一个学生可以选修多门课程,一门课程也可以有多个学生。

Student类

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类

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

<!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类

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;
    }
}

插入示例数据

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();
            }
        }
    }
}

查询示例数据

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();
            }
        }
    }
}

多对多关系的详细解释

  1. 实体类定义

    • Student 类和 Course 类通过 @ManyToMany 注解来定义多对多的关系。
    • Student 类中使用 @JoinTable 注解来定义中间表,指定了关联的学生和课程的外键。
    • Course 类中使用 mappedBy 属性来指定关系维护由 Student 类中的 courses 属性来负责。
  2. Hibernate配置文件

    • 标准的Hibernate配置文件,用于数据库连接和映射类的配置。
  3. HibernateUtil类

    • 一个实用类,用来创建和返回 SessionFactory 实例。
  4. 插入示例数据

    • 创建 StudentCourse 对象,并建立多对多关系。
    • 保存数据到数据库中。
  5. 查询示例数据

    • 查询所有学生和他们所选修的课程,以及所有课程和选修这些课程的学生。

到此这篇关于Hibernate处理多对多关系的实现示例的文章就介绍到这了,更多相关Hibernate 多对多内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文