将 null 传递给 JPA OneToOne Persist

Passing null to JPA OneToOne Persist

我有一个人力资源系统,可以添加和更新数据库。每当我传递一个空值时,我的 JPA 关系在坚持和合并方面都有问题。在我们的要求中,它可以为空,但是当我向它输入一个空值时,例如部门会发生以下错误:

[RollbackException: Error while committing the transaction] Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: models.db.Employee.Department -> models.db.Department

这里是我的实体供参考class Employee.class

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

@Id
public Integer EMPLOYEE_ID;

public String FIRST_NAME;

public String LAST_NAME;

@OneToOne
@JoinColumn(name= "JOB_ID")
public Job Job;

@OneToOne
@JoinColumn(name="MANAGER_ID")
public Employee Manager;

@OneToOne
@JoinColumn(name= "DEPARTMENT_ID")
public Department Department;

}

Job.class

@Entity
@Table(name="JOBS")
public class Job {

@Id
public String JOB_ID;

public String JOB_TITLE;

}

Department.class

@Entity
@Table(name="DEPARTMENTS")
public class Department {

@Id
public Integer DEPARTMENT_ID;

public String DEPARTMENT_NAME;

@OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name="MANAGER_ID")
public Employee Manager;
}

AppModel.class保存()

public void save () {
int intSize = listSize + 1;
for (int i= 0; i < intSize; i++) {
Employee employee = new Employee();

Job job = new Job();
job.JOB_ID = employees.get("empJobId" + i);

Department dept = new Department();
dept.DEPARTMENT_ID = ParseUtil.stringToInt(employees.get("empDeptId" + i));

Employee manager = new Employee();
manager.EMPLOYEE_ID = ParseUtil.stringToInt(employees.get("empMgrId" + i));

Integer intId =  ParseUtil.stringToInt(employees.get("empId" + i));
employee.EMPLOYEE_ID = intId;
employee.FIRST_NAME = employees.get("empFirstName" + i);
employee.LAST_NAME = employees.get("empLastName" + i);
employee.Job = job;
employee.Department = dept;
employee.Manager = manager;
EmpDomain.updateEmp(employee);
}
}

和EmpDomain.updateEmp()

public static void updateEmp(Employee employee) {
  JPA.em().merge(employee);
}

我只是 play 2 的新手,jpa 持久性所以我不知道如何修复异常错误请帮助。

您似乎在尝试将这些依赖关系映射为双向。

在那种情况下,您必须告诉持久性提供者哪个是关系的拥有方。

例如,如果 Employee 是拥有方,那么您应该将映射更改为:

@OneToOne(mappedBy = "Manager", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
public Department Department;

此外,如果您要从 Employee 实体合并,那么您至少应该放置持久化和合并级联选项。