2

我有 2 个实体:News 和 NewsComment

@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

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

4

1 回答 1

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

在拥有方你不应该声明级联行为。这是在拥有方完成的。

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

希望这对你有用。

于 2012-08-21T15:32:03.187 回答