2012-09-16 46 views
1

我有兩個實體JPA:防止級聯操作[保存,刪除...]

@Entity 
@Table(name="parent") 
public class Parent { 
    @Id 
    String uuid; 

    @ElementCollection(fetch=FetchType.EAGER) 
    @CollectionTable(
     name="child", 
     [email protected](name="parent_uuid", insertable=false, updatable=false) 
) 

    @Column(name="uuid") 
    private Set<String> childrenUuids = new HashSet<String>(); 
} 

@Entity 
@Table(name="child") 
public class Child { 
    @Id 
    String uuid; 

    @Column(name="parent_uuid") 
    String parentUuid; 

} 

現在,當我堅持家長,在childrenUuids孩子們自動持久,因爲多對一的關係。我想阻止所有的操作對Parent進行級聯(例如persist,remove ...),是否可以使用JPA?我一直在研究幾天,但找不到答案。謝謝。

回答

1

您應該使用@OneToMany而不是@ElementCollection。 @OneToMany默認不會級聯。就我所知,@ElementCollection總是級聯的,因爲「@ElementCollection定義了基本類型或嵌入類的實例集合」,並且基本類型/可嵌入類型被認爲是其父類的一個組成部分。

+0

謝謝。問題是我的Child對象在實際情況下很大,實際上我只需要它的一列。加載整個Child對象對我來說成本太高。無論如何,要實現沒有級聯的CollectionTable的相同效果? –

+0

顯然@OneToMany是用於關係,並且集合不是關係,所以不應該使用它。 – DataNucleus

0

@ElementCollection始終會級聯。我最終通過爲@ElementCollection實現我的解決方案來解決此問題。我仍然使用JPA批註,相反,我在@ElementCollection上添加@Transient使JPA忽略它。那麼我將我的實現作爲JPA後加載偵聽器添加到每個實體,這會在實體加載後填充每個集合。