I trying to do the relationship between Category and Publication classes (OneToMany) and I need to delete all the Publications that belong to an specific Category. I don't know if I missing some annotations but this is my error when I execute the query:
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".
My source code is as follow:
Category class:
@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
}
Publication class:
@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
}
Query to delete categories:
@Override
public void deleteCategory(int id) {
sessionFactory.getCurrentSession()
.createQuery("DELETE FROM Category WHERE id="+id).executeUpdate();
}
Thanks in advance people.