Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to eagerly load lazy fields with JPA 2.0?

I have an entity class that has a lazy field like this:

@Entity
public Movie implements Serializable {
    ...
    @Basic(fetch = FetchType.LAZY)
    private String story;
    ...
}

The story field should normally be loaded lazily because it's usually large. However sometimes, I need to load it eagerly, but I don't write something ugly like movie.getStory() to force the loading. For lazy relationship I know a fetch join can force a eager loading, but it doesn't work for lazy field. How do I write a query to eagerly load the story field?

like image 504
Zhao Yi Avatar asked Aug 31 '11 02:08

Zhao Yi


1 Answers

The one possible solution is:

SELECT movie 
FROM Movie movie LEFT JOIN FETCH movie.referencedEntities
WHERE...

Other could be to use @Transactional on method in ManagedBean or Stateless and try to access movie.getReferencedEntities().size() to load it but it will generate N+1 problem i.e. generating additional N queries for each relationship which isn't too efficient in many cases.

like image 92
Michał Ziobro Avatar answered Sep 19 '22 15:09

Michał Ziobro