2015-04-07 66 views
0

我發展我的項目,將在數據庫中更新實體的服務器端邏輯。但是這個實體參考了另一個實體的列表。更新數據庫時,某些條目被拆除JPA

所以,比如我有一個實體Test像這樣的:

@Entity 
    public class Test { 

     @Id 
     @Column(name = "idTest", nullable = false) 
     @GeneratedValue(strategy = GenerationType.AUTO) 
     private Long id; 
     private String name; 

     @OneToMany(mappedBy = "idTest", targetEntity = Test2.class, fetch = FetchType.LAZY) 
     private Collection<Test2> test2Collection; 
    } 

其具有Test2實體引用。

@Entity 
public class Test2 { 

    @Id 
    @Column(name = "idTest2", nullable = false) 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 
    private String field1; 
    private String field2; 

    @ManyToOne 
    @JoinColumn(name = "idTest", referencedColumnName = "idTest") 
    private Test idTest; 
} 

就我而言,我更新的集合Test進入test2Collection,最終我取出它的一些Test2條目。

EntityManager簡單merge方法沒有檢測到一些條目已被刪除,當我稱它通過新的更新Test條目。

我正在考慮通過Test條目之間的差異來跟蹤從test2Collection中刪除的條目,然後再更新數據庫和新的Test條目進行更新。

但我不知道這是這樣做的唯一的(和最佳)的方式。任何人有另一個想法?

+0

難道你不需要例如OneToMany上的「cascade = CascadeType.ALL」嗎? –

回答

2

在你的關係,你必須添加orphanRemoval,然後如果你刪除集合中的一個元素,堅持測試,刪除了收集將被自動刪除TEST2表的元素。

@OneToMany(orphanRemoval = true, mappedBy = "idTest", targetEntity = Test2.class, fetch = FetchType.LAZY) 
    private Collection<Test2> test2Collection; 
+0

謝謝!這種方法比我想象的要好得多! –

相關問題