vlio20
vlio20

Reputation: 9295

Hibernate eager loading with query

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

Upvotes: 1

Views: 1167

Answers (1)

simon at rcl
simon at rcl

Reputation: 7344

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.

Upvotes: 1

Related Questions