[英]delete everything in a many-to-many relationship (JPA)
I have the following model (reduced): 我有以下模型(简化):
@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;
}
I have a database where videos are connected to multiple tags and vice versa. 我有一个将视频连接到多个标签的数据库,反之亦然。 I want to delete all videos and cascade it to delete all tags as well. 我想删除所有视频并将其级联以删除所有标签。 Calling remove on a Video entity results in a cycle and after a few round of going back and forth between a tag and a video, the java compiler prints a stack dump of the cycle. 在Video实体上调用remove会导致一个循环,并且在标签和视频之间进行了几轮往返之后,Java编译器会打印该循环的堆栈转储。
How can I remove a video / all videos using JPA , preferably by removing all videos and cascading the remove to the tags. 如何使用JPA删除视频/所有视频,最好通过删除所有视频并将删除操作级联到标签来实现。
The actions are: 这些动作是:
Remove videos entities also remove tag entities because cascade anotation in Video Class. 删除视频实体也会删除标签实体,因为视频类中的级联注释。
//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(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.