我有两个实体如下:
@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
,同时有EmployeeRpository
和WorkFlowStatusRepository
。我的服务方法类似于:
@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
表的条目时没有生成任何语句。我做错了什么?如何在同一个调用中在第一个实体中进行插入,然后更新第二个实体?
1条答案
按热度按时间7gcisfzg1#
在工作流状态实体中,
在员工实体中,
参考文献:
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