1

The model is that a user can have many LoginSessions (LogginSession can be related to only one user).
What I am trying to achieve is bring the user with related LoginSession (which's token provided in the query). All of that I am trying to do with only one query, and to do so I want to use eager loading, here is my code:

I have this code:

    LoginSession loginSession = new LoginSession();
    loginSession.setToken(sessionToken);

    //Example loginSessionExample = Example.create(loginSession);

    Criteria crit = session.createCriteria(User.class);
    crit.createAlias("userLoginSession", "session");
    crit.add(Restrictions.eq("session.token", sessionToken));
    crit.setMaxResults(1);
    crit.setFirstResult(0);
    crit.setFetchMode("loginSession", FetchMode.JOIN);

List<?> usersList = (List<?>) crit.list(); // first query

if(usersList.size() == 1)
{
    User user = (User) usersList.get(0);
    LoginSession loginSession = (LoginSession) user.getUserLoginSession().toArray()[0]; //second query
    ...

The problem is that there are 2 quires that are being executed (see comments in the provided code).

What am I doing wrong with my Criteria and how can I make to be a one query?

Thanks

1 Answer 1

1

This is the way Hibernate (and most ORMs) work: they lazy load relations from other tables only when actually required. If they didn't, you can have sizeable portions of your database loaded when all you want is one object.

Lazy Loading can be disabled, relation by relation, as described in this StackExchange answer. However, it means that it will always be disabled, so make sure that this is really a bad thing before you do it.

I would not say that the situation you have described is a bad thing.

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

Comments

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.