ManyToOne reference loading with JPA/Hibernate

Posted on January 8, 2008
Tags: Archer, java, JPA

In this example an InvestigationType has many SampleType’s. If I load an InvestigationType via em (entity manager) find it also loads the samples.

  1. InvestigationType inv2 = (InvestigationType) em.find(
  2. InvestigationType.class, inv.getId());
  3. System.out.println(“Inv2 ID=”+inv2.getId());
  4. System.out.println(“Inv2 Title=”+inv2.getTitle());
  5. assertTrue(inv2.getSample().size() == 2);

However, if I load a SampleType the investigation field is null, unless I refresh the object.

  1. // Get a sample
  2. SampleType s3 = (SampleType) em.find(
  3. SampleType.class, inv2.getSample().get(0).getId());
  4. em.refresh(s3);
  5. System.out.println(convertDataToXmlString(s3));
  6. InvestigationType inv3 = s3.getInvestigation();
  7. assertNotNull(inv3);

From my understanding I should not have to do this as the fetching should be the same in both instances, ie resolving the parent by default. Similarly, if I query for both objects the references are correctly loaded.

List items = em.createQuery(“SELECT i, s FROM au.edu.archer.schemas.datadeposition.SampleType s, IN(s.investigation) i WHERE s.id=2”).getResultList();

If someone could tell me why this is so, please let me know. Else, at least I have a working example now.

Powered by ScribeFire.