我有以下型号(减少):
@Entity
public class Video {
@ManyToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
@JoinTable(name = "video_tag", joinColumns = {
@JoinColumn(name = "video_id", referencedColumnName = "id") }, inverseJoinColumns = {
@JoinColumn(name = "tag_id", referencedColumnName = "id") })
private Set<Tag> tags;
}
@Entity
public class Tag {
@ManyToMany(mappedBy="tags", fetch=FetchType.LAZY)
private Set<Video> videos;
}
我有一个数据库,其中视频连接到多个标签,反之亦然。我想删除所有视频并级联它以删除所有标签。在视频实体上调用remove会导致一个循环,在标记和视频之间往返几轮后,java编译器会打印循环的堆栈转储。
如何使用 JPA 删除视频/所有视频,最好删除所有视频并将删除级联到标记。
答案 0 :(得分:1)
行动是:
删除视频实体也会移除标记实体,因为在视频类中进行级联转换。
//Remove relationships
List<Video> videoList;
for (Video v : videoList) {
for(Tag t : video.getTags()){
t.getVideos.remove(v);
v.getTags.remove(t);
}
}
//Update owner entities
for (Video v : videoList) {
Session sess = HibernateUtil.getSessionFactory().openSession();
Transaction tx = sess.beginTransaction();
sess.update(v);
tx.commit();
sess.close();
}
//Remove owner entities
for (Video v : videoList) {
Session sess = HibernateUtil.getSessionFactory().openSession();
Transaction tx = sess.beginTransaction();
sess.delete(v);
tx.commit();
sess.close();
}