当前位置: 首页 > 教程 > JPA >

JPA多对多映射

精华
小牛编辑
172浏览
2023-03-14

多对多映射表示集合值关联,其中任何数量的实体可以与其他实体的集合关联。 在关系数据库中,一个实体的任何行可以被引用到另一个实体的任意数量的行。

完整的项目目录结构如下所示 -

@ManyToMany 示例

在这个例子中,我们将创建学生和图书馆之间的多对多关系,以便可以为任何数量的学生发放任何类型的书籍。

这个例子包含以下步骤 -

第1步:com.yiibai.mapping包中创建一个实体类Student.java,包含学生ID(s_id)和学生姓名(s_name),其中包含一个使用@@ManyToMany注解的List类型的Library类对象。

文件:Student.java 的代码如下所示 -

package com.yiibai.mapping;

import java.util.List;

import javax.persistence.*;

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int s_id;
    private String s_name;

    @ManyToMany(targetEntity = Library.class)
    private List lib;

    public Student(int s_id, String s_name, List lib) {
        super();
        this.s_id = s_id;
        this.s_name = s_name;
        this.lib = lib;
    }

    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }

    public List getLib() {
        return lib;
    }

    public void ListLib(List lib) {
        this.lib = lib;
    }

    public int getS_id() {
        return s_id;
    }

    public void ListS_id(int s_id) {
        this.s_id = s_id;
    }

    public String getS_name() {
        return s_name;
    }

    public void ListS_name(String s_name) {
        this.s_name = s_name;
    }
}

第2步: 在包含book id(b_id)book name(b_name)@ManyToMany注释的com.yiibai.mapping包下创建另一个实体类Library.java,其中包含List类型的Student类对象。

文件:Library.java 的代码如下所示 -

package com.yiibai.mapping;

import java.util.List;

import javax.persistence.*;

@Entity
public class Library {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int b_id;
    private String b_name;

    @ManyToMany(targetEntity = Student.class)
    private List stud;

    public Library(int b_id, String b_name, List stud) {
        super();
        this.b_id = b_id;
        this.b_name = b_name;
        this.stud = stud;
    }

    public Library() {
        super();
        // TODO Auto-generated constructor stub
    }

    public int getB_id() {
        return b_id;
    }

    public void ListB_id(int b_id) {
        this.b_id = b_id;
    }

    public String getB_name() {
        return b_name;
    }

    public void ListB_name(String b_name) {
        this.b_name = b_name;
    }

    public List getStud() {
        return stud;
    }

    public void ListStud(List stud) {
        this.stud = stud;
    }

}

第3步: 将实体类和其他数据库配置映射到persistence.xml文件中。

文件:persistence.xml 的代码如下所示 -

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="book_issued">
        <class>com.yiibai.mapping.Student</class>
        <class>com.yiibai.mapping.Library</class>
        <properties>
            <property name="javax.persistence.jdbc.driver"
                value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:mysql://localhost:3306/testdb?serverTimezone=UTC" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password"
                value="123456" />
            <property name="eclipselink.logging.level" value="SEVERE" />
            <property name="eclipselink.ddl-generation"
                value="create-or-extend-tables" />
        </properties>
    </persistence-unit>

</persistence>

com.yiibai.mapping包下创建一个持久化类ManyToManyExample,用于将实体对象与数据保持一致。

文件:ManyToManyExample.java 的代码如下所示 -

package com.yiibai.mapping;

import java.util.ArrayList;

import javax.persistence.*;
import com.yiibai.mapping.Student;
import com.yiibai.mapping.Library;

public class ManyToManyExample {

    public static void main(String[] args) {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("books_issued");
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();

        Student st1 = new Student(1, "Maxsu", null);
        Student st2 = new Student(2, "Xiaonew", null);

        em.persist(st1);
        em.persist(st2);

        ArrayList<Student> al1 = new ArrayList<Student>();
        ArrayList<Student> al2 = new ArrayList<Student>();

        al1.add(st1);
        al1.add(st2);

        al2.add(st1);
        al2.add(st2);

        Library lib1 = new Library(101, "Data Structure", al1);
        Library lib2 = new Library(102, "DBMS", al2);

        em.persist(lib1);
        em.persist(lib2);

        em.getTransaction().commit();
        em.close();
        emf.close();

    }

}

程序输出结果

程序执行完成后,下面的表格在MySQL工作台下生成。

  • Student表 - 此表包含学生详细信息。要获取数据,请在MySQL中运行select * from student查询。结果如下所示 -
mysql> select * from student;
+------+---------+
| S_ID | S_NAME  |
+------+---------+
|    2 | Xiaonew |
|    1 | Maxsu   |
+------+---------+
2 rows in set
  • Library表 - 这个表格代表学生和图书库之间的映射。 要获取数据,请在MySQL中运行select * from library查询。结果如下所示 -
mysql> select * from library;
+------+----------------+
| B_ID | B_NAME         |
+------+----------------+
|  102 | DBMS           |
|  101 | Data Structure |
+------+----------------+
2 rows in set
  • Library_student表 - 此表包含库的详细信息。要获取数据,请在MySQL中运行select * from library_student查询。
mysql> select * from library_student;
+--------------+-----------+
| Library_B_ID | stud_S_ID |
+--------------+-----------+
|          101 |         1 |
|          101 |         2 |
|          102 |         1 |
|          102 |         2 |
+--------------+-----------+
4 rows in set