Home > database >  JPA/Hibernate/SpringBoot: Inserting @OneToMany relationship entities
JPA/Hibernate/SpringBoot: Inserting @OneToMany relationship entities

Time:11-09

I'm struggling with inserting @OneToMany entities in the JPA-Hibernate setup.

There are two associated table 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?

CodePudding user response:

How do I handle inserting/updating @OneToMany entities? Is this possible?

If you want the DB to generate the primary key values for you, you need to ask for it by using the @GeneratedValue annotation

@Entity(name = "employee")
class Employee {
     
     @Id
     @Column(name = "id")
     @GeneratedValue // mean -> "Hey, DB, give me an ID"!
     private Long id;

Same applies for EmployeeLocation

More details can be found here

If this does not fully solve your problem, leave a comment.

CodePudding user response:

In your EmployeeLocation entity (detail) you cannot have as primary key the master's primary key, it needs its own. As follows:

@Entity(name = "employee_location")
class EmployeeLocation {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "employee_location_id")
  private Integer id;

  @ManyToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "employee_id", referencedColumnName = "id", insertable = false, updatable = false)
  private Employee employee;

} 
  • Related