1

I wonder what is the reason of calling method PersistenceUnitUtil#isLoaded(Object).

JPA Documentation says that it can help to determine the load state of an entity belonging to persistence unit, but it also mentions that

An entity is considered loaded if all attributes for which FetchType.EAGER has been specified have been loaded.

So, are there situations when not all attributes with FetchType.EAGER are loaded? What are they? I am only sure that it will work for entities returned by EntityManager#getReference() method. Are there more of them?

Maciej Dobrowolski
  • 10,083
  • 3
  • 40
  • 58
  • I imagine that it may be useful in some edge cases of mutithreaded environment. – Piotr Gwiazda Jul 23 '14 at 20:29
  • I always assumed it was to complement the use of getReference vs find methods. getReference is allowed to return you unfetched entities where it only has the pk set. isLoaded would tell you if the entity was already fetched or not. – Chris Jul 24 '14 at 13:38

1 Answers1

0

One of the great uses for this is integration tests. If you want to make sure that when a certain method is called, whatever comes back has certain things loaded, this is a good way to do it.

There are a couple of ways that a relationship set to use FetchType.EAGER can end up not loaded.

  1. When using a @NamedEntityGraph, if you specify the hint to the query as javax.persistence.fetchgraph, then the JPA provider should only load the relationships named in the entity graph. This is the difference between that and javax.persistence.loadgraph, which loads relationships not specified in the entity graph using whatever fetch type they already had.

    The problem, and the reason that I said the provider "should" only load those relationships, is that the JPA spec allows the provider to always load more than the specification requires. Hibernate, specifically, ignores the recommended behavior for fetchgraph, and treats it the same as loadgraph.

  2. For Hibernate criteria queries you can override and set the fetch mode of any relationship explicitly using setFetchMode(). I don't know about other providers.

Maybe there are others?

Ah, and as I was looking around for some more details I see that this has already all been said in another StackOverflow question here:

Ignore a FetchType.EAGER in a relationship

Community
  • 1
  • 1
MorganP
  • 123
  • 1
  • 10