2
我正在尋找一種方法來保存數據庫生成Id(@GeneratedValue
)的位置,並將該值級聯到組合鍵的一部分的子對象。比方說,我們有以下Parent
:JPA/Hibernate用複合鍵保存孩子依賴於父
@Entity
@Table("PARENT")
public class Parent {
private long id;
private List<Child> children;
@Id
@GeneratedValue
@Column(name="...")
public long getId() {
return this.id
}
public void setId(long id) {
this.id = id;
}
@OneToMany(mappedBy="key.parent", cascade= { CascadeType.ALL })
public List<Child> getChildren() {
return this.children;
}
}
的小孩:
@Entity
@Table("CHILD")
public class Child {
private CompositeKey key;
private String value;
@EmbeddedId
public CompositeKey getKey() {
return this.key
}
public void setKey(CompositeKey key) {
this.key = key;
}
// .. basic mapping of value column
}
和複合鍵:
@Embeddable
public class CompositeKey key {
private String type;
private Parent parent;
@Column(name="TYPE")
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
@ManyToOne
@JoinColumn("PARENT_ID") // FK in the Child table
public Parent getParent() {
return this.parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
有誰知道這是如何工作的,其中ID爲Parent
能作爲CompositeKey
Child
中210
最後,我最終修改我們的數據庫並使用UUID生成器來設置子對象的鍵。我嘗試了一些頂級的搜索結果,但最終決定我需要繼續前進。 – rynmrtn