【发布时间】:2015-04-07 01:06:05
【问题描述】:
我正在我的项目的服务器端开发一个逻辑,它将更新数据库中的实体。但是这个实体引用了另一个实体的列表。
所以,例如我有一个像这样的实体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。
@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;
}
就我而言,我正在更新集合 test2Collection 的 Test 条目,最终我将删除其中的一些 Test2 条目。
来自EntityManager 的简单merge 方法在我调用它传递新的更新Test 条目时没有检测到某些条目已被删除。
我正在考虑通过在 Test 条目之间进行差异来跟踪从 test2Collection 中删除的条目,然后再使用要更新的新 Test 条目更新数据库。
但我不确定这是唯一(也是最好的)方法。其他人有其他想法吗?
【问题讨论】:
-
您不只需要 OneToMany 上的“cascade = CascadeType.ALL”吗?
标签: java spring hibernate jpa entitymanager