Hibernate急于加载查询 [英] Hibernate eager loading with query

查看:79
本文介绍了Hibernate急于加载查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模型是 user 可以有许多 LoginSessions (LogginSession可以只与一个用户有关)。

我想要实现的是为用户提供相关的LoginSession(这是查询中提供的令牌)。
我只用一个查询来完成所有这些工作,为此我想使用预先加载,这里是我的代码:

我有这段代码:

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

//示例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);

列表<?> usersList =(List<>)crit.list(); //首先查询

if(usersList.size()== 1)
{
User user =(User)usersList.get(0);
LoginSession loginSession =(LoginSession)user.getUserLoginSession()。toArray()[0]; //第二个查询
...

问题是有两个quires是(请参阅提供的代码中的注释)。



我在做什么错在我的Criteria中,我怎样才能成为一个查询?



谢谢

解决方案

这是Hibernate(和大多数ORM)的工作方式:仅在实际需要时才从其他表加载关系。如果他们没有,你可以在你想要的只有一个对象的时候加载数据库的大部分内容。



懒惰加载可以被禁止,如关系描述在这个StackExchange答案。然而,这意味着它会一直被禁用,所以在你做这件事之前要确保这是一件坏事。



我不会说你遇到的情况描述是一件坏事。


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

解决方案

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.

这篇关于Hibernate急于加载查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆