ManyToMany - 删除Join表中的条目

时间:2014-03-28 13:29:28

标签: java hibernate jpa

我有两个实体并且它们具有多对多关系,我想要实现的是当我删除一个实体时,也应该删除在连接表中引用它的所有条目。我该怎么做?

到目前为止,我有:

@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;

在拥有实体中:

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

在逆向中,但是当我尝试删除反向的时,我得到的错误是连接表中有字段引用它。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

首先包含在@ManyToMany注释中 级联= CascadeType.ALL。

之后确保调用类具有正在进行的有效事务,并且您的目标实体在被删除时附加到PersistenceContext,如果不是这样,您可能必须为该实体进行合并,同时检查如果您的数据库正在执行生成的SQL:

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());
    }   
}