I'm struggling with inserting @OneToMany
entities in the JPA-Hibernate setup.
There are two associated tables with one of the table having the foreign key as the primary key of the source table.
employee
- id (PK)
employee_location
- employee_id (FK to employee)
Here are my entities:
Employee
@Entity(name = "employee")
class Employee {
@Id
@Column(name = "id")
@GeneratedValue()
private Long id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "employee_id", referencedColumnName = "id")
private List<EmployeeLocation> employeeLocations;
}
Employee Location
@Entity(name = "employee_location")
class EmployeeLocation {
@Id
@Column(name = "employee_id")
private Long employeeId;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "employee_id", referencedColumnName = "id", insertable = false, updatable = false)
private Employee employee;
}
Saving the entities:
List<EmployeeLocation> locations = Arrays.asList(new EmployeeLocation(), new EmployeeLocation());
Employee employee = new Employee();
employee.setLocations(locations);
employee.save(); // Throws exceptions
Which throws me this error:
org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save():
I tried changing @Entity
to @Embeddable
and removed the @Id
on EmployeeLocation
, but it gave me other Unmapped entity
exceptions.
How do I handle inserting/updating @OneToMany
entities? Is this possible?