Lucas
Lucas

Reputation: 3281

ManyToMany - delete entries in a Join table

I have two entities and they have many-to-many relationship, what I want to achieve is when I delete one entity, then all entries referencing it in a join table should be removed as well. How do I do that?

So far I have:

@JoinTable(name = "interviewer_technology",
        joinColumns = {
        @JoinColumn(name = "interviewer_id", referencedColumnName = "id")
},
inverseJoinColumns = {
        @JoinColumn(name = "technology_id", referencedColumnName = "id")
})
@ManyToMany(fetch = FetchType.LAZY)
private Collection<Technology> technologies;

in the owning entity and:

@ManyToMany(mappedBy = "technologies", fetch = FetchType.LAZY)
private Collection<Interviewer> interviewers;

in the inverse one, but when I try to delete the inverse one, I get the error that there are fields in join table referencing it. How can I tackle this problem?

Upvotes: 2

Views: 1582

Answers (1)

guilhebl
guilhebl

Reputation: 8990

first include in your @ManyToMany annotations cascade=CascadeType.ALL.

After that make sure the calling class has a valid transaction going on and that your target entity is attached to your PersistenceContext at the moment it's being deleted, if not so, you might have to do a merge for the entity, check also if the resulting SQLs are being executed by your DB:

Sample delete method of Business Class:

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void delete(T entity) throws ServiceException {
    try {

        if (!entityManager.contains(entity)) {
            entity = entityManager.merge(entity);   
        }           
        entityManager.remove(entity);       

    } catch (Exception se) {
        se.printStackTrace();
        throw new ServiceException("Error while deleting from DB " + 
                entity.getClass().getSimpleName() + " id: " + entity.getId());
    }   
}

Upvotes: 1

Related Questions