Mariusz
Mariusz

Reputation: 1985

Is possible do not fetch eager relation in JPA?

I have relation annotated as following:

@OneToMany( fetch = FetchType.EAGER )

Is possible to do not fetch this relation without changing default fetch type to lazy? I ask obout it because I improve existing application and I don't want to change existing entities and their annotations. In my case I don't need to fetch this relation and fetching it is very computer power consuming so I would like to avoid it. One way to solve it is createing second redundant entity which does not have this relation. Is there a better way?

I use Hibernate as persistence provider.

Upvotes: 0

Views: 927

Answers (2)

Shailendra
Shailendra

Reputation: 9102

JPA Implementers such as Hibernate use the global fetch plans like these to create SQL's (to load entities later for e.g., for loading entity by Id instead of creating SQL's every time when required) at EntityManagerFactory bootstrap time and there is not yet any configuration to override these global fetch plans. The two solutions that come to mind are

  1. Change your mapping - Highly recommended and cannot be stressed enough. Eager fetch plans should be scrutinized at all times and avoided at best. Believe me this is experience talking :-)
  2. Use Criteria API - as Illustrated by @Amit - however this would mean that you would need to change the access pattern in your code.If your Parent entity is related to another Entity in the graph and you simply call getParent from the Root entity, it will load the related childrens of Parent too in one shot (using a prebuilt join query if you are using Hibernate) and this would be useless. Whereever you need to relate Parent entity, mark it Lazy and avoid it's getter - intead use Criteria query.

Upvotes: 2

Amit Parashar
Amit Parashar

Reputation: 1457

I am not sure on this, Try specifying the fetch type explicitly in your query, some thing like this:

Criteria crit = session.createCriteria(ParentClass.class);
crit.add(Restrictions.eq("id", id));
crit.setFetchMode("childProperty", FetchMode.LAZY);

Upvotes: 1

Related Questions