Hibernate级联删除孤儿

时间:2012-08-21 15:04:06

标签: hibernate cascading-deletes all-delete-orphan

我有2个实体:新闻和新闻评论

@Entity
@Table(name = "news", schema = "city")
public class News {

        private Set<CommentNews> comments = new HashSet<CommentNews>();
        ...
    @OneToMany(cascade={javax.persistence.CascadeType.ALL})
    @Cascade(CascadeType.DELETE_ORPHAN)
    @JoinColumn(name="news_id")
    public Set<CommentNews> getComments() {
        return comments;
    }
}

@Entity
@Table(name = "comment_news", schema = "city")
public class CommentNews {
private News news;            
    ...

    @ManyToOne
@Cascade(CascadeType.DELETE_ORPHAN)
@JoinColumn(name = "news_id")
public News getNews() {
    return news;
}
}

和像这样的代码:

public void delete(int id) {
        T obj = null;
        session = HibernateUtil.openSession();
        try {
            session.beginTransaction();
            obj = (T) session.get(persistentClass, id);
            session.delete(obj);
            session.getTransaction().commit();
        } catch (HibernateException e) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }
    }

我得到了

Hibernate: update city.comment_news set news_id=null where news_id=?
    WARN : org.hibernate.util.JDBCExceptionReporter - SQL Error: 1048, SQLState: 23000
    ERROR: org.hibernate.util.JDBCExceptionReporter - Column 'news_id' cannot be null
    ERROR: org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
    org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 
Column 'news_id' cannot be null

我想要级联删除新闻和评论新闻一起

1 个答案:

答案 0 :(得分:7)

此处的映射不正确:

在拥有方面,您应该使用mappedBy来显示映射(JoinColumn)位于另一侧。你不应该在双方都有JoinColumn。

您应该使用包含orphanRemoval属性的JPA注释作为OneToMany的一部分。

@Entity
@Table(name = "news", schema = "city")
public class News {
    @OneToMany(mappedBy = "news", cascade={javax.persistence.CascadeType.ALL}, orphanRemoval = true)
    public Set<CommentNews> getComments() {
        return comments;
    }
}

并且在拥有方面,您不应该声明级联行为。这是在自有方面完成的。

@Entity
@Table(name = "comment_news", schema = "city")
public class CommentNews {
    @ManyToOne
    @JoinColumn(name = "news_id")
    public News getNews() {
        return news;
    }
}

希望对你有用。