我正在项目的服务器端开发一个逻辑,该逻辑将更新数据库中的实体。但是这个实体引用了另一个实体的列表。
因此,例如我有一个像这样的实体测试
:
@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
条目的 Collection test2Collection
,并最终删除其中的一些 Test2
条目.
当我调用传递新更新的Test
条目时,EntityManager
中的简单merge
方法不会检测到某些条目已被删除。
我想通过在使用新的 Test
更新数据库之前在 Test
条目之间进行比较来跟踪从 test2Collection
中删除的条目条目待更新。
但我不确定这是唯一(也是最好)的方法。还有人有其他想法吗?
最佳答案
在你的关系中,你必须添加orphanRemoval,那么如果你删除集合中的一个元素并持久化Test,集合上删除的元素将自动删除Test2表。
@OneToMany(orphanRemoval = true, mappedBy = "idTest", targetEntity = Test2.class, fetch = FetchType.LAZY)
private Collection<Test2> test2Collection;
关于java - 删除某些条目时更新数据库 JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29482073/