2

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.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks I found this article, but you are damn right :) eubauer.de/kingsware/2011/02/10/… Is there also a way to prevent a ManyToOne relation to be fetched at all? In another query I would like the ManyToOne relation to be not fetched (even if there might be somebody calling "getUser(s)"). Is there are similar way to tell openJPA in a JPQL query to NOT fetch an object ?
No. If you want that, use a DTO, not an entity.
Thanks for the answer JB, unfortunately the naming convention with the "s" at the user is a design error that is very old and hard to fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.