How to eagerly load lazy fields with JPA 2.0?

Zhao Yi picture Zhao Yi · Aug 31, 2011 · Viewed 13.2k times · Source

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?

Answer

Bozho picture Bozho · Aug 31, 2011

I'd try Hibernate.initialize(movie). But calling the getter (and adding a comment that this forces initialization) is not that wrong.