title: Hibernate - ManyToOne - Save - org.hibernate.TransientObjectException:
body: <p>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:</p>
  
  <p>Table structures we are using:</p>
  
  <pre><code>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
  }
  </code></pre>
  
  <p>(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?</p>
  
  <p>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.</p>
  
  <p>Any suggestions on best practice to be followed for this?</p>
  
  <p>Thank you in advance</p>