I have a question concerning the lazy fetch function in Hibernate JPA. My test structure is quite simple: a company object which has products. Those products shall be fetched lazily.
Now what happens is that after a persist and an immediate find on the EntityManager a company object is returned which does not have a products proxy (products is simply null). Only after I detach the company object and then read it via find does it contain a proxied collection. I find it strange that the EntityManager returns an object which does not have proxied property objects where laziness is required.
The second test case is similar but here I use merge to persist the object. The javadoc for merge states that merge returns a “managed instance” so here I would expect the object to have the proxies set. Nonetheless the test fails because products is null.
I’m using hibernate 3.6.0-final for this test. Is my understanding wrong or is this a problem with hibernate?
Code:
@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int companyId;
private String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
private List<Product> produts;
}
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int productId;
@ManyToOne
private Company company;
}
public class Test2Jpa {
@PersistenceContext
private EntityManager em;
@Test
public void testProductsPersistNewCompany() throws Exception {
Company company = new Company();
company.setName("test");
em.persist(company);
em.detach(company); // doesn't work without this
Company companyFromDb = em.find(Company.class, company.getCompanyId());
assertNotNull(companyFromDb.getProduts());
}
@Test
public void testProductsMergeNewCompany() throws Exception {
Company company = new Company();
company.setName("test");
Company newCompany = em.merge(company);
assertNotNull(newCompany.getProduts()); // fails
}
}