Search code examples
jpapersistencejpqlopenjpa

Understanding FetchType.Lazy, force in JPQL query (OpenJPA)


I have an Entity like this:

public class Configuration {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    @Element(name = "user_id", data = true, required = false)
    private Users users;
}

What I would like is to define a query where one time the LazyLoading is performed, and another time not.

But the query:

@NamedQuery(name = "getNondeletedConfiguration", query = "SELECT c FROM Configuration c  "
                     + "LEFT JOIN c.users users WHERE c.deleted = false"),

Does NOT load the Users into the object.

The way to force loading the users object is to access the attributes somewhere in the code. However this is not working, I don't want this behaviour. I would like to control the lazy loading only based on my JPQL statements. I don't want openJPA to magically load objects because it detects an access through a get method somewhere in the Java Code.

I guess this is a common issue and I simply misunderstand something. However, I can't find docs about the problem.


Solution

  • You need to add the fetch keyword to load the association:

    select c from Configuration c left join fetch c.users where c.deleted = false
    

    Note that the name Users for an entity representing one user is really badly chosen, and very confusing. Same for the field name users. You should remove the final s, which makes every reader think that a configuration has many users.