JPA級聯持久化


級聯持久化用於指定如果實體持久化,則其所有關聯的子實體也將被持久化。 以下語法用於執行級聯永續性操作 -

@OneToOne(cascade=CascadeType.PERSIST)

JPA級聯持久化範例

在這個例子中,我們將建立兩個相互關聯的實體類,但要建立它們之間的依賴關係,我們將執行級聯操作。

這個例子包含以下步驟 -

第1步:com.yiibai.jpa.student包下建立一個名為StudentEntity.java的實體類,其中包含屬性:s_ids_names_age以及標記為級聯規範的Subject型別的物件。

檔案: StudentEntity.java -

package com.yiibai.jpa.student;

import javax.persistence.*;
import com.yiibai.jpa.subject.Subject;

@Entity
@Table(name = "student")
public class StudentEntity {

    @Id
    private int s_id;
    private String s_name;
    private int s_age;

    @OneToOne(cascade = CascadeType.PERSIST)
    private Subject sub;

    public Subject getSub() {
        return sub;
    }

    public void setSub(Subject sub) {
        this.sub = sub;
    }

    public StudentEntity(int s_id, String s_name, int s_age, Subject sub) {
        super();
        this.s_id = s_id;
        this.s_name = s_name;
        this.s_age = s_age;
        this.sub = sub;
    }

    public StudentEntity() {
        super();
    }

    public int getS_id() {
        return s_id;
    }

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

    public String getS_name() {
        return s_name;
    }

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

    public int getS_age() {
        return s_age;
    }

    public void setS_age(int s_age) {
        this.s_age = s_age;
    }

}

第2步:com.yiibai.jpa.subject包下建立另一個名為Subject.java的實體類。

檔案:Subject.java -

package com.yiibai.jpa.subject;

import javax.persistence.*;

@Entity
@Table(name = "subject")
public class Subject {

    private String name;
    private int marks;
    @Id
    private int s_id;

    public Subject(String name, int marks, int s_id) {
        super();
        this.name = name;
        this.marks = marks;
        this.s_id = s_id;
    }

    public Subject() {
        super();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMarks() {
        return marks;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    public int getS_id() {
        return s_id;
    }

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

}

現在,將實體類和其他資料庫組態對映到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="Student_details">
        <class>com.yiibai.jpa.student.StudentEntity</class>  
    <class>com.yiibai.jpa.subject.Subject</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.jpa.cascade包下建立一個名為StudentCascade.java的持久化類,以便將實體物件與資料保持一致。

檔案:StudentCascade.java -

package com.yiibai.jpa.cascade;

import javax.persistence.*;

import com.yiibai.jpa.student.*;
import com.yiibai.jpa.subject.Subject;

public class StudentCascade {

    public static void main(String[] args) {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("Student_details");

        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();

        StudentEntity s1 = new StudentEntity();
        s1.setS_id(101);
        s1.setS_name("Maxsu");
        s1.setS_age(20);

        StudentEntity s2 = new StudentEntity();
        s2.setS_id(102);
        s2.setS_name("James");
        s2.setS_age(22);

        Subject sb1 = new Subject();
        sb1.setName("ENGLISH");
        sb1.setMarks(80);
        sb1.setS_id(s1.getS_id());

        Subject sb2 = new Subject();
        sb2.setName("Maths");
        sb2.setMarks(75);
        sb2.setS_id(s2.getS_id());

        s1.setSub(sb1);
        s2.setSub(sb2);

        em.persist(s1);// No need to perform persist operation separately for different entities.
        em.persist(s2);

        em.getTransaction().commit();

        em.close();
        emf.close();

    }

}

註 - student表中的主鍵(即s_id)將作為subject表中的外來鍵處理,以維持兩個表之間的關係。

輸出結果

程式執行完畢後,在MySQL工作台下生成以下表格。

  • student表 - 要獲取資料,在MySQL中執行select * from student。得到結果如下 -

    mysql> select * from student;
    +------+-------+--------+----------+
    | S_ID | S_AGE | S_NAME | SUB_S_ID |
    +------+-------+--------+----------+
    |  102 |    22 | James  |      102 |
    |  101 |    20 | Maxsu  |      101 |
    +------+-------+--------+----------+
    2 rows in set
    
  • subject表 - 要獲取資料,在MySQL中執行select * from subject。得到結果如下 -

    mysql>  select * from subject ;
    +------+-------+---------+
    | S_ID | MARKS | NAME    |
    +------+-------+---------+
    |  102 |    75 | Maths   |
    |  101 |    80 | ENGLISH |
    +------+-------+---------+
    2 rows in set