1

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>();
3
  • Is there anything in the join table except FKs to the two other tables? You'll probably need to post your hibernate configuration for the tables. Commented Oct 15, 2010 at 10:36
  • No, only the IDs of project and person. I updated my initial post and added the annotations. Commented Oct 15, 2010 at 10:46
  • Another solution here instead of making bidirectional relation, is to mark the relation with @Cascade(CascadeType.DELETE_ORPHAN). Then you can just remove the project by removing it from the projects collection in Person. Commented Apr 10, 2012 at 15:14

1 Answer 1

1

I can answer my question: I need to set the persons to null:

p.setPersons(null);

and everything is okay.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.