Filus1025
Filus1025

Reputation: 43

JPA Collection of objects with Lazy loaded field

What is the good way to force initialization of Lazy Loaded field in each object of collection?

At this moment the only thing that comes to my mind is to use for each loop to iterate trough collection and call getter of that field but it's not very effiecient. Collection can have even 1k objects and in that case every iteration will fire to db.

I can't change the way I fetch objects from DB.

Example of code.

public class TransactionData{

@ManyToOne(fetch = FetchType.LAZY)
private CustomerData customer;
...
}

List<TransactionData> transactions = getTransactions();

Upvotes: 1

Views: 386

Answers (2)

stg
stg

Reputation: 2797

You may define Entity Graphs to overrule the default fetch types, as they are defined in the Mapping.

See the 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 the following query the adresses will now be 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 that way you are able to define specific fetch behaviour for each differet use-case.

See also:

By the way: afaik do most JPA provider perform eager loading of @XXXtoOne relations, even if you define the mapping as lazy. The JPA spec does allow this behaviour, as lazy loading is always just a hint that the data may or may not be loaded immediately. Eager Loading on other other hand has to be performed immediately.

Upvotes: 1

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

What you can do is something like this:

//lazily loaded
List<Child> childList = parent.getChild(); 

// this will get all the child in memory of that particular Parent
Integer childListSize = childList.size();

But if you eager load then all the child will be loaded for each of the parents. This should be your best bet.

Upvotes: 0

Related Questions