我正在努力@OneToMany在 JPA-Hibernate 設定中插入物體。
有兩個關聯表,其中一個表以外鍵作為源表的主鍵。
employee
- id (PK)
employee_location
- employee_id (FK to employee)
這是我的物體:
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;
}
保存物體:
List<EmployeeLocation> locations = Arrays.asList(new EmployeeLocation(), new EmployeeLocation());
Employee employee = new Employee();
employee.setLocations(locations);
employee.save(); // Throws exceptions
這給我帶來了這個錯誤:
org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save():
我嘗試更改@Entity為@Embeddable并洗掉了@Idon EmployeeLocation,但它給了我其他Unmapped entity例外。
如何處理插入/更新@OneToMany物體?這可能嗎?
uj5u.com熱心網友回復:
如何處理插入/更新 @OneToMany 物體?這可能嗎?
如果您希望 DBprimary key為您生成值,則需要使用@GeneratedValue批注來請求它
@Entity(name = "employee")
class Employee {
@Id
@Column(name = "id")
@GeneratedValue // mean -> "Hey, DB, give me an ID"!
private Long id;
同樣適用 EmployeeLocation
可以在此處找到更多詳細資訊
如果這不能完全解決您的問題,請發表評論。
uj5u.com熱心網友回復:
在您的EmployeeLocation物體(詳細資訊)中,您不能將主鍵作為主鍵,它需要自己的主鍵。如下:
@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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/352940.html
