While I try to save top level entity (using JPA), do I need to get the ManyToOne mapped entity freshly from database and set it or cannot I just set Id (of manyToOne mapped entity and save top level entity? When do not get fresh entity it throws: org.hibernate.TransientObjectException:
Table structures we are using:
DEPARTMENT(DEPARTMENT_ID BIGINT, NAME VARCHAR(128))
EMPLOYEE(EMPLOYEE_ID BIGINT, NAME VARCHAR(128), DEPARTMENT_ID BIGINT)
Entities:
class Department
{
@Id
Long departmentId;
String name;
@Version
Long versionNumber;
}
class Employee
{
@Id
Long employeeId;
String name;
@ManyToOne
Department department;
@Version
Long versionNumber
}
(both classes have setter and getter methods for all fields and default constructor, constructor which takes primary key as argument) Now if I want to save Employee with departmentId (say 100), do I need to get the Department record first and then set it in employee?
Cannot I create instance of Department directly (by setting primary key(departmentId)) and set Department instance in Employee and save Employee? When I do this it is throwing org.hibernate.TransientObjectException.
Any suggestions on best practice to be followed for this?
Thank you in advance