Asad Khan
Asad Khan

Reputation: 513

Relation needed on demand while using lazy loading in hibernate

I have project where all the models relations (either 1:m or 1:1) fetch types are defined as lazy. Now consider I have a model called M that has three relation a,b and c and all are 1:m. Now I have three services: Service-A Service-B Service-C

If Service-A return model M then its relation a must be populated although other b,c contains proxy model. If Service-B return model M then its relation b must be populated although other a,c contains proxy model. same as for Service-C

Can anyone know how to accomplished that ?

Another scenario here if there is only one Service and user provide as parameter to load relation a or b or c then how to accomplish that ?

Upvotes: 0

Views: 271

Answers (1)

Peter Šály
Peter Šály

Reputation: 2933

Simplest way is to populate them inside transaction:

in ServiceA entity.getCollectionB().size()

in ServiceB entity.getCollectionC().size()

See other ways: http://www.thoughts-on-java.org/5-ways-to-initialize-lazy-relations-and-when-to-use-them/

EDIT: Lazy loading of one to one relation won't work with entity graph either. With or without it you will need bytecode instrumentation. Optimizing columns read is not so important as optimizing row reads. See: http://www.thoughts-on-java.org/jpa-21-entity-graph-part-1-named-entity/#comment-219

Upvotes: 1

Related Questions