i have 2 tables with a ManyToMany relationship. Projects and Persons. I have 2 lists, one with projects and one with persons. In one list are all the persons from the person table in the other all the projects from the project table. Each Project has a list with all persons in it and each person a list with all projects that person is in. If i now delete a person the person gets deleted from the person table and from the "person_in_project" table in my database. The problem i have is that if i now re-read the tables:
Query query = em.createQuery("select p from Project p");
projects = query.getResultList();
Query query = em.createQuery("select p from Person p");
persons = query.getResultList();
the person that was deleted (and so doesn't exist anymore) is still in it's projects.
I found out that this doesn't happen if i disable the shared cache, but this can't be the answer. So what to do
JPA states that you must maintain both sides of a bidirectional relationship or the entites will not reflect what is in the database. In this case, when you remove a person, you must also remove all references to that person or the cache will be inconsistent.
a) remove the person from each project that has a reference to it. This is recommended.
b) refresh each project after the transaction completes (ie using a refresh hint on a findall projects type query) to deal with the inconsistent data from not doing A
c) Don't have the project->person relationship in the project entity and instead query for it when needed
d) Disable the shared cache.
Options b to D could involve extra queries and have performance implications.