Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JPA bidirectional OneToMany Problem

 
Nick Shrine
Greenhorn
Posts: 11
Hibernate Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Mark Spritzler
ranger
Sheriff
Posts: 17309
11
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you add the Supervisor to the Project, do you also add the Project to the list that is in the Supervisor object? To set both sides of the relationship? Try that.

Mark
 
Nick Shrine
Greenhorn
Posts: 11
Hibernate Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes that is the way to do it, need to add project to supervisor's collection of projects then em.merge(supervisor)
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!