我有 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
我想级联删除新闻和评论新闻一起