2012-01-19 32 views
2

我正在尋找一種方法來保存數據庫生成Id(@GeneratedValue)的位置,並將該值級聯到組合鍵的一部分的子對象。比方說,我們有以下ParentJPA/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

的一部分保存並作爲FK的一部分設置在 Child中210

回答

0

你有沒有解決過這個問題?

我有一個類似的問題,試圖設置一個複合ID的東西,也被保存。

對我來說似乎是工作的是使用和@PrePersist註釋來運行一個方法之前,組合鍵被保存,並在該方法創建/設置複合ID - 因爲在那個時候引用的項目有一個ID。

這看起來好像會起作用嗎? (也許爲你工作,如果這仍然是一個問題)

+0

最後,我最終修改我們的數據庫並使用UUID生成器來設置子對象的鍵。我嘗試了一些頂級的搜索結果,但最終決定我需要繼續前進。 – rynmrtn

相關問題