spring-data-jpa 如何在Spring Data JPA中通过一次调用保存一对多关系的两个实体

x6492ojm  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(211)

我有两个实体如下:

@Entity
@Table(name="Employee")
public class Employee {

    //...

    @OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
    private Set<WorkFlowStatus> workFlowStatuses;

    //mapping with some other tables as well
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="location_id", nullable=false)
    private Set<LocationDetails> locationDetails;

    // getters and setters
}

@Entity
@Table(name="WorkFlowStatus")
public class WorkFlowStatus {

    //...
    @ManyToOne
    @JoinColumn(name="employee_id", nullable=false)
    private Employee employee;

    public WorkFlowStatus() {}

    // getters and setters
}

Employee表中有一个workFlowStatus_Id列,它也存在于WorkFlowStatus表中,并且是该表的主键。基本上,我想首先在WorkFlowStatus表中创建新条目,然后用这个新插入条目的ID更新Employee表的workFlowStatus_Id列。因此,我在服务层中创建了一个用@Transactional注解的方法。另外,我有Autowired,同时有EmployeeRpositoryWorkFlowStatusRepository。我的服务方法类似于:

@Service
public class EmpService {
 @Autowired
    EmployeeRpository employeeRpository;

    @Autowired
    WorkFlowStatusRepository workFlowStatusRepository;

    @Transactional
    public void updateEmployeeWorkflowStatus(Long empId) throws SQLException {
        //getting Emp object first
        Employee emp = employeeRpository.findById(empId);
        WorkFlowStatus workFlowStatus = saveWorkFlowStatus(emp);
        updateEmpWorkFlowStatus(emp, workFlowStatus);
    }

    private WorkFlowStatus saveWorkFlowStatus(Employee emp) {
        //create new Object
        WorkFlowStatus workFlowStatus = new WorkFlowStatus();
       //set other properties and fetched emp in created object
        workFlowStatus.setEmployee(emp);
        return workFlowStatusRepository.save(workFlowStatus);
    }

    private void updateEmpWorkFlowStatus(Employee emp, WorkFlowStatus workFlowStatus) {

        //set saved workFlow in existing emp object
        emp.setWorkFlowStatus(emp.getWorkFlowStatus().add(workFlowStatus));
        employeeRpository.save(emp);
    }
}

我已经启用了Hibernate日志记录。我可以看到在WorkFlowStatus表中进行插入时生成了插入语句,但在更新Employee表的条目时没有生成任何语句。我做错了什么?如何在同一个调用中在第一个实体中进行插入,然后更新第二个实体?

7gcisfzg

7gcisfzg1#

在工作流状态实体中,

@ManyToOne 
@JoinColumn(name="employee_id", nullable=false , insertable=false, updatable=false)
private Employee employee;

在员工实体中,

@OneToMany(targetEntity = WorkFlowStatus.class,cascade=CascadeType.ALL)
@JoinColumn(name = "employee_id",nullable = false)
private Set<WorkFlowStatus> workFlowStatuses;

参考文献:
https://www.baeldung.com/hibernate-one-to-many
Hibernate Spring - @OneToMany - Foreign key is not getting stored in database
Hibernate is inserting null value in foreign key field when saving a unidirectional one to many mapping
https://github.com/riskop/jpa_hibernate_problem_parent_id_is_not_filled_by_hibernate

相关问题