2

I got a problem that goes against my understanding of how it supposed to work. I have a Arquillian-test that tests a repository-method with a JPA query.

The test persists an object, and then persists an another object with the first persisted object in a field. Then it calls the repository-method. Next the test detaches (and clear the entitymanager, checks that the object is not contained in the em etc etc). Last the test checks if the related object is there or not (it shouldn't since the query is not supposed to read the relation).

As expected, when looking in the debugger, the related object is null, but when the assert actually uses the getRelatedObject-method, is loads the related object.

Pseudocode to clarify (i hope):

FirstObject f = new FirstObject();
em.persist(f);
SecondObject s = new SecondObject();
s.setFirstObject(f);
em.persist(f);
MyRepo r = new MyRepo();
SecondObject result = r.runQuery(f.getId());
em.detach(result); //result.getFirstObject is null
em.clear();
assertIsNull(result.getFirstObject()); //loads first object and test fails

Is it my understanding that is wrong, should the related object still load? I expected a LazyInit-exception.

If i'm my understanding is wrong, how to verify that a query doesn't populate related object I don't won't?

(yes, using dto-objects instead of the entity is better, I know... we have had that discussion and I was overruled)

Roland
  • 5,328
  • 10
  • 37
  • 55

1 Answers1

4

The book Pro JPA 2 (Apress, p160) notes

"The behavior of accessing an unloaded attribute when the entity is detached is not defined. Some vendors might attempt to resolve the relationship, while others might simply throw an exception or leave the attribute uninitialized."

I do not have experience of EclipseLink personally and can find anything definitive in the documentation in this area however the following links all suggest that EclipseLink will try and resolve the relationship when you access a lazy association on a detached collection.

Eclipselink Lazy Loading

http://issues.apache.org/jira/browse/OPENJPA-2483

http://blog.ringerc.id.au/2012/06/jpa2-is-very-inflexible-with-eagerlazy.html

Community
  • 1
  • 1
Alan Hay
  • 22,665
  • 4
  • 56
  • 110