删除某些条目时更新数据库 JPA
Update database when some entries were removed 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
条目更新数据库之前在 Test
条目之间进行差异来跟踪从 test2Collection
中删除的条目。
但我不确定这是唯一(也是最好)的方法。还有其他人有其他想法吗?
在你的关系中,你必须添加orphanRemoval,然后如果你删除集合中的一个元素并持久化Test,集合上删除的元素将自动删除Test2 table。
@OneToMany(orphanRemoval = true, mappedBy = "idTest", targetEntity = Test2.class, fetch = FetchType.LAZY)
private Collection<Test2> test2Collection;
我正在我的项目的服务器端开发一个逻辑,它将更新数据库中的一个实体。但是这个实体引用了另一个实体的列表。
所以,例如我有一个像这样的实体 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
条目更新数据库之前在 Test
条目之间进行差异来跟踪从 test2Collection
中删除的条目。
但我不确定这是唯一(也是最好)的方法。还有其他人有其他想法吗?
在你的关系中,你必须添加orphanRemoval,然后如果你删除集合中的一个元素并持久化Test,集合上删除的元素将自动删除Test2 table。
@OneToMany(orphanRemoval = true, mappedBy = "idTest", targetEntity = Test2.class, fetch = FetchType.LAZY)
private Collection<Test2> test2Collection;