• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

JPA bidirectional OneToMany Problem

 
Greenhorn
Posts: 11
Hibernate Netbeans IDE Tomcat Server
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic