2
我在創建父對象和子對象時遇到了問題,並在使用JPA和休眠的情況下將其持久保存到數據庫中。父類看起來像這樣:休眠JPA父母與子組合違反父子女
@Entity
@Table(name = "PUser")
public final class User {
@Id
@Column(name = "ID", unique = true, nullable = false, updatable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
}
的子對象使用的化合物鍵,場是父的ID之一:
@Entity
@Table(name = "PAttribute")
public final class Attribute {
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "domain", column = @Column(name = "domain", nullable = false, length = 128)),
@AttributeOverride(name = "name", column = @Column(name = "name", nullable = false, length = 128)),
@AttributeOverride(name = "userid", column = @Column(name = "userid", nullable = false)) })
private AttributePk pk;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userid", nullable = false, insertable = false, updatable = false)
private User user;
}
複合鍵類之中:
@Embeddable
public class AttributePk implements java.io.Serializable {
private static final long serialVersionUID = -7003721226789641149L;
@Column(nullable = false, length = 128)
private String domain;
@Column(nullable = false, length = 128)
private String name;
@Column(nullable = false)
private long userid;
}
現在,當我創建一個新用戶並添加一個附件,然後嘗試保存該對象圖時
User user = new User("[email protected]", "xyz");
user.setScreenName("joe1bloggs");
user.addAttribute("domain", "name", 212);
target.saveAndFlush(user);
我得到的異常
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`fta_portal_user/PAttribute`, CONSTRAINT `userId` FOREIGN KEY (`userid`) REFERENCES `PUser` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
顯然屬性子對象不具有用戶對象集的ID。
我知道我可以做以下工作,但看起來很奇怪,我不能僅僅創建一個對象層次結構,並且Hibernate會計劃如何設置相應的ID。我懷疑這是沒有辦法的,因爲saveAndFlush()返回一個新的實例,而不僅僅是更新輸入參數的版本。
User user = new User("[email protected]", "xyz");
user.setScreenName("joe1bloggs");
// target is an JpaRepository intergafe
user = target.saveAndFlush(user);
user.addAttribute("domain", "name", 212);
target.saveAndFlush(user);
任何人有任何想法,或只是一個生活的情況嗎?
感謝
尼克
編輯:您可以得到這個通過添加@MapsId註釋子類(感謝axtavt的答覆)工作。即
@MapsId("userId")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId", nullable = false, insertable = false, updatable = false)
private User user;
非常感謝,如果我稍微調整它,那會有用(請參閱原始問題中的編輯) – nickcodefresh