I have two entity classes with a bidirectional relationship thus:
class Supervisor {
@OneToMany
private Collection<Project> projects;
}
class Project {
@ManyToOne
private Supervisor supervisor;
}
Here is my
test case:
public testCreateProject() throws Exception {
EntityManagerFactory emf = Persistence.createEntityManager("PU");
/* Retrieve the current list of projects */
EntityManager em = emf.createEntityManager();
Supervisor s = (Supervisor) em.find(Supervisor.class, 1);
int beforeSize = s.getProjects().size();
em.close();
/* Create a new project and save it */
Project p = new Project();
p.setSupervisor(s);
em = emf.createEntityManager();
em.getTransactio().begin();
em.persist(p);
em.getTransaction().commit();
em.close();
/* Retrieve updated list of projects */
em = emf.createEntityManager();
s = (Supervisor) em.find(Supervisor.class, 1);
int afterSize = s.getProjects().size();
em.close();
/* After adding a new project there should be +1 */
assertEquals(beforeSize + 1, afterSize);
}
The test always fails as beforeSize always equals afterSize. It is not re-reading the projects collection from the database.
Only after running the test again does the projects collection size increase by 1 indicating that there is some caching of the s object somewhere?
Any clues?