Hibernate eager loading with query

拈花ヽ惹草 提交于 2019-12-24 06:49:53

问题


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:


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.



来源:https://stackoverflow.com/questions/25823552/hibernate-eager-loading-with-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!