Hibernate级联删除孤儿

use*_*528 2 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

@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;
}
}
Run Code Online (Sandbox Code Playgroud)

和这样的代码:

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我明白了

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
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*nes 6

这里的映射不正确:

在拥有方面,您应该使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在拥有方面,你不应该声明级联行为.这是在自有方面完成的.

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

希望对你有用.

  • 如果我没有拥有`@ OneToMany`映射,我该怎么办?我只有`@ ManyToOne`侧面映射. (2认同)