JPA Object Relational Mapping--Cascading Operations

Object mapping relationship is divided into one-way relationship and two-way relationship. One-way relationship only exists on one object and two-way relationship exists on both objects.

1. One-way relationship

public class Department implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer departmentId;

    private String departmentCode;
    
    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn
    private List<Employee> employeeList;
}

In the absence of @JoinColumn, an additional intermediate relationship table will be added to maintain the two object relationships from which only two tables will be added, and the relationship will be maintained by the Employee table.By default, jpa uses primary keys to associate and foreign key constraints are added to subtables.

2. One-way relationship uses code Association

Primary keys typically use self-increasing IDs when designing table structures, but when making subtable associations you do not want to use self-increasing IDs for relationship maintenance due to distributed structure reasons, you can customize field code s to maintain relationships as follows:

public class Department implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer departmentId;

    private String departmentCode;

    @OneToMany(cascade = {CascadeType.ALL})
    @JoinColumn(name = "departmentCode", referencedColumnName = "departmentCode")
    private List<Employee> employeeList;
}

A department_code field is added to the employee table to maintain the association. Note: From the SQL in the add operation, it can be seen that employee updates the update relationship field after insert.

Hibernate: insert into department (department_code, department_name) values (?, ?)
Hibernate: insert into employee (employee_code, employee_name) values (?, ?)
Hibernate: insert into employee (employee_code, employee_name) values (?, ?)
Hibernate: update employee set department_code=? where employee_id=?
Hibernate: update employee set department_code=? where employee_id=?

3. Two-way Relations

public class Department implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer departmentId;

    private String departmentCode;

    @OneToMany(cascade = {CascadeType.ALL}, mappedBy = "department")
    private List<Employee> employeeList;
}

public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer employeeId;

    private String employeeCode;

    @ManyToOne
    private Department department;
}

Using mappedBy removes the intermediate relationship table and employee maintains the department relationship.

Matters needing attention: 1. In the add operation, the child object employee must set the primary object, otherwise the foreign key relationship is not maintained at the database level, such as:

@Test
public void add(){
    Department department = Department.builder()
            .departmentCode("D001")
            .departmentName("Department 1")
            .build();

    Employee employee = Employee.builder()
            .employeeCode("E001")
            .employeeName("Employee 1")
            .build();
    // If this is not done, there will be no association        
    employee.setDepartment(department);
    
    List<Employee> employeeList = new ArrayList<>();
    employeeList.add(employee);

    department.setEmployeeList(employeeList);
    departmentRepository.save(department);
}

2. This setting does not require an additional update relationship

Hibernate: insert into department (department_code, department_name) values (?, ?)
Hibernate: insert into employee (department_department_id, employee_code, employee_name) values (?, ?, ?)
Hibernate: insert into employee (department_department_id, employee_code, employee_name) values (?, ?, ?)

3. Close the parent object toString in the child object to avoid infinite loop calls

4. Two-way Relationships Use code Association

Similar to one-way relationships with additional update operations code association, mappedBy cannot be used together when using JoinColumn

5. Cascade Operation Settings

  • CascadeType.PERSIST: Cascade save, save employee object while department is saved
  • CascadeType.MERGE: Cascade updates, treat department and employee as a whole, and update any object that changes
  • CascadeType.REMOVE: Cascade Delete
    • When the delete primary object is not set, the child object simply removes the relationship; remove child object only removes the relationship; adding orphanRemoval = true removes the child object of remove
    • When set, the delete primary object and the child object are also deleted
  • CascadeType.REFRESH: Cascade refresh (less used) to avoid dirty data in concurrent scenarios
  • CascadeType.DETACH: Cascade offloading (less used)
  • CascadeType.ALL: All of the above should be set carefully to avoid confusion.

6. Source Code

https://gitee.com/hypier/barry-jpa/tree/master/jpa-section-2

Tags: Programming Hibernate less SQL Database

Posted on Tue, 17 Mar 2020 12:49:24 -0400 by Zanne