将null传递给JPA OneToOne Persist

时间:2017-10-02 07:35:48

标签: java hibernate jpa playframework jpa-2.0

我有一个HR系统,可以添加和更新数据库。每当我在其上传递空值时,我在持久化和合并中的JPA关系中存在问题。在我们的要求中,它可以是可空的,但即使我输入一个空值,例如部门发生以下错误:

  

[RollbackException:提交事务时出错]       引起:org.hibernate.TransientObjectException:对象引用未保存的瞬态实例 - 保存瞬态实例   在冲洗之前:models.db.Employee.Department - > models.db.Department

这里是我的实体类 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 save()

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);
}

我只是玩游戏2的新手,jpa坚持所以我不知道如何修复异常错误请帮忙。

1 个答案:

答案 0 :(得分:1)

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

在这种情况下,你必须告诉持久性提供者,它是该关系的拥有者/拥有者。

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

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

如果您要从Employee实体合并,那么您应该至少保留并合并级联选项。