Reputation: 6606
If I have the following Entity object which has several foreign key relationships how do I handle form submission when I don't get the relationship object back in the request.
The entity might look something like this:
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "middle_name")
private String middleName;
@Column(name = "login_id")
private String loginId;
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "department_id")
private Department department;
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "employment_type_id")
private EmploymentType employmentType;
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "citizenship_id")
private Citizenship citizenship;
public Employee() {
}
}
But this is the HTTP POST request I'll be receiving.
id: 1
firstName: Bob
lastName: Dole
middleName: Trump
loginId: bdole
departmentId: 1
employmentTypeId: 2
citizenship_id: 4
JPA wants to save the relationship object, not the ID. However doing all those look ups also seems inefficient, turning the IDs into the required objects to persist. Is there a better way to handle this?
Upvotes: 0
Views: 41
Reputation: 1567
Use getReference http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html#getReference%28java.lang.Class,%20java.lang.Object%29
It calls the entityManager to load customer object using the id and then set that onto the customer history. In most cases this call would return a proxy with just the id embedded.
Department department = entityManager.getReference(Department.class, departmentId);
Employee employee = new Employee();
employee.setDepartment(department);
Upvotes: 1