如何优化这个GORM查询 [英] How to optimize this GORM query

查看:236
本文介绍了如何优化这个GORM查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询,它使2个数据库查询。我是GORM的新手,不知道如何使用标准或where子句或其他方法将其优化为1个查询。我也使用springsecurity,并有一个用于登录安全性的User类。我有一个带User对象的Profile类:

  class Profile {
用户用户
}

在我的控制器中,会话存储用户标识。当我想加载配置文件来更新它时,我的代码是:

$ p $ def $ user $ User.get(springSecurityService.principal。 id)//第一个数据库查询
def domainObject = Profile.findByUser(user)//第二个数据库查询

我通过试验和错误尝试了一些查询变体,但似乎无法找到不会产生错误的变体。这似乎是微不足道的。伪查询应该是'让我获得具有该用户标识的profile.user的配置文件'。

解决方案

您可以使用 load 方法避免第一个数据库查询:

  def user = User.load(springSecurityService.principal.id)
def domainObject = Profile.findByUser(user)

因为 load 不会触发数据库查找,除非您访问 id 以外的任何其他属性,但这就是 findByUser 所需的全部内容,因为它是外键。


I have a query which makes 2 database queries. I am new to GORM and don't know how to optimize it into 1 query using criteria, or a where clause or something else. I'm using springsecurity as well and have a User class for login security. I have a Profile class with a User object:

class Profile {
   User user
}

In my controller the session stores the user id. When I want to load the profile to update it my code is currently:

def user = User.get(springSecurityService.principal.id) // 1st db query
def domainObject = Profile.findByUser(user) // 2nd db query

I've tried a few query variations through trial and error but can't seem to find one that doesn't generate an error. This seems like it would be trivial. The pseudo-query would be 'get me the profile for the profile.user that has this user id'.

解决方案

You can use the load method to avoid the first database query:

def user = User.load(springSecurityService.principal.id)
def domainObject = Profile.findByUser(user)

This works because load doesn't trigger a database lookup until you access any property other than the id, but that's all that's needed for the findByUser since it's the foreign key.

这篇关于如何优化这个GORM查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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