java - JPA Collection of objects with Lazy loaded field -
what way force initialization of lazy loaded field in each object of collection?
at moment thing comes mind use for each
loop iterate trough collection , call getter of field it's not effiecient. collection can have 1k objects , in case every iteration fire db.
i can't change way fetch objects db.
example of code.
public class transactiondata{ @manytoone(fetch = fetchtype.lazy) private customerdata customer; ... } list<transactiondata> transactions = gettransactions();
you may define entity graphs overrule default fetch types, defined in mapping.
see example below
@entity @namedentitygraph( name = "person.addresses", attributenodes = @namedattributenode("addresses") ) public class person { ... @onetomany(fetch = fetchtype.lazy) // default fetch type private list<address> addresses; ... }
in following query adresses loaded eagerly.
entitygraph entitygraph = entitymanager.getentitygraph("person.addresses"); typedquery<person> query = entitymanager.createnamedquery("person.findall", person.class); query.sethint("javax.persistence.loadgraph", entitygraph); list<person> persons = query.getresultlist();
in way able define specific fetch behaviour each differet use-case.
see also:
- http://www.thoughts-on-java.org/jpa-21-entity-graph-part-1-named-entity/
- https://docs.oracle.com/javaee/7/tutorial/persistence-entitygraphs001.htm
by way: afaik jpa provider perform eager loading of @xxxtoone
relations, if define mapping lazy. jpa spec allow behaviour, lazy loading hint data may or may not loaded immediately. eager loading on other other hand has performed immediately.
Comments
Post a Comment