Hello!
I have a JPA/Hibernate problem with a n:m relation (Project <-> Person) with a join table. The Project is the mapping owner and has a (cascade = CascadeType.ALL).
Now I want to remove a project which is associated with a Person, so there is an entry in the Project_Person join table, but I get a
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
because the entry of the Project_Person table is not deleted before the project should be removed.
Here is the removeProject method:
public void removeProject(int projectId){
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session sess = sessionFactory.getCurrentSession();
Transaction tx = sess.beginTransaction();
try {
Project p = (Project)sess.createQuery("from Project where id = "+projectId).list().get(0);
sess.delete(p);
tx.commit();
}
catch (IndexOutOfBoundsException ex) {System.out.println("exception: "+ex);}
}
All is inside the transaction, so there is not a problem. But why does the sess.selete(p) not automatically remove the entry from the join table?
Does anyone know? Best Regards Tim.
Update:
Person.java:
@ManyToMany(mappedBy="persons")
private Set<Project> projects = new HashSet<Project>();
Project.java:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "Project_Person",
joinColumns = {@JoinColumn(name="project_id", referencedColumnName="id")},
inverseJoinColumns = {@JoinColumn(name="person_id", referencedColumnName="id")}
)
private Set<Person> persons = new HashSet<Person>();