NoobProgrammer NoobProgrammer - 3 years ago 156
Java Question

Passing null to JPA OneToOne Persist

I have an HR System that will add and update the database. I have a problem in my JPA relationship in persist and merging whenever I would pass a null value on it. In our requirement it can be nullable, but when even I enter a null value to it for example the departments the following error occurs:

[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

For reference here are my entity class

public class Employee {

public Integer EMPLOYEE_ID;

public String FIRST_NAME;

public String LAST_NAME;

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

public Employee Manager;

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



public class Job {

public String JOB_ID;

public String JOB_TITLE;



public class Department {

public Integer DEPARTMENT_ID;

public String DEPARTMENT_NAME;

@OneToOne(cascade = {CascadeType.ALL})
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;

And EmpDomain.updateEmp()

public static void updateEmp(Employee employee) {

Im only a newbie on play 2, jpa persistance so i dont know how to fix the exception error please help.

Answer Source

It seems that you are trying to map those dependencies as bi-directional.

In that case you have to tell the persistence provider which is the owning / owned side of the relationship.

If Employee is the owned side for example then you should change the mapping to:

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

also if you are merging from the Employee entity then you should put at least persist and merge cascading option.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download