我试图建立类别和出版物类(OneToMany)之间的关系,并且我需要删除属于特定类别的所有出版物。 我不知道是否缺少一些注释,但这是我执行查询时的错误:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute update query org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973) org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852) javax.servlet.http.HttpServlet.service(HttpServlet.java:618) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) javax.servlet.http.HttpServlet.service(HttpServlet.java:725) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.hibernate.exception.ConstraintViolationException: could not execute update query.
org.postgresql.util.PSQLException: ERROR: update or delete on table "category" violates foreign key constraint "fkf5bea17d42c4af41" on table "publication" Detail: Key (id)=(190) is still referenced from table "publication".
我的源代码如下:
类别类别:
@Entity
@Table(name = "category")
public class Category {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private String description;
@OneToMany(mappedBy="category", orphanRemoval=true)
private List<Publication> publications;
// Getters and Setters
}
出版类别:
@Entity
@Table(name = "Publication")
public class Publication {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String title;
private String content;
@ManyToOne
@JoinColumn(name = "id_category")
private Category category;
// Getters and Setters
}
删除类别的查询:
@Override
public void deleteCategory(int id) {
sessionFactory.getCurrentSession()
.createQuery("DELETE FROM Category WHERE id="+id).executeUpdate();
}
提前感谢大家。
最佳答案
您需要将删除操作级联到发布:
@OneToMany(mappedBy="category", orphanRemoval=true, cascade = CascadeType.ALL)
private List<Publication> publications;
<小时/>
编辑:
由于添加级联并不能解决您的问题,并且您正在使用 Hibernate,因此添加特定于 Hibernate 的级联注释可能会有所帮助。在这种情况下,您不需要上面的 JPA 参数:
@OneToMany(mappedBy="category", orphanRemoval=true)
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.ALL)
private List<Publication> publications;
这破坏了到不同对象关系映射框架的可移植性,因为它不再是纯粹的 JPA - 但它在过去的某些情况下对我有帮助。
关于java - Hibernate 注解映射、JPA 孤儿删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25996988/