Vjeetje
Vjeetje

Reputation: 5384

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.

How can I remove a video / all videos using JPA, preferably by removing all videos and cascading the remove to the tags.

Upvotes: 1

Views: 1092

Answers (1)

Daniel Rch.
Daniel Rch.

Reputation: 170

The actions are:

  1. Breakdown relationships (object schema)
  2. Update owner entity (video in this case)
  3. 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();
    }
    

Upvotes: 1

Related Questions