2

在控制器中我有这个查找器

User.findByEmail('test@test.com')

并且有效。

即使我写也有效

User.findByEmail(null)

但如果我写

User.findByEmail(session.email)

并且 session.email 没有定义(ergo 为空)它抛出异常

groovy.lang.MissingMethodException: No signature of method: myapp.User.findByEmail() is applicable for argument types: () values: []

这种行为对吗?

如果我评估“session.email”它给我 null 所以我认为它必须像我写 User.findByEmail(null) 时那样工作

更奇怪的是......

如果我在 groovy 控制台中运行此代码:

import myapp.User
User.findByEmail(null)

它返回一个电子邮件为空的用户,但如果我再次运行相同的代码,它会返回

groovy.lang.MissingMethodException: No signature of method: myapp.User.findByEmail() is applicable for argument types: () values: []
4

3 回答 3

4

您不能使用标准findBySomething动态查找器来搜索空值,您需要改用findBySomethingIsNull版本。尝试

def user = (session.email ? User.findByEmail(session.email)
                          : User.findByEmailIsNull())

请注意,即使User.findByEmail(null)每次都能正常工作,它也不一定会在所有数据库上为您提供正确的结果,因为它findBySomething(null)会转化为

WHERE something = null

在底层 SQL 查询中,并且根据 SQL 规范null不等于其他任何东西(甚至不等于null)。您必须something is null在 SQL 中使用来匹配空值,这就是findBySomethingIsNull()转换为的内容。

您可以在类中编写一个静态实用程序方法User来将此检查收集到一个地方

public static User byOptEmail(val) {
  if(val == null) {
    return User.findByEmailIsNull()
  }
  User.findByEmail(val)
}

然后User.byOptEmail(session.email)在您的控制器中使用。

于 2012-12-07T12:25:14.717 回答
1

grails nabble 论坛的 Jeff Brown 发现了我的问题。这是一个 GORM 错误。见吉拉

有关此线程的更多信息

这个jira也是

于 2012-12-07T15:55:21.853 回答
0

我尝试使用调试器,它看起来应该可以正常工作,就像你写的那样。也许 groovy 本身在这里有点困惑,尝试以这种方式帮助它:

User.findByEmail( session['email'] )
于 2012-12-07T10:18:09.973 回答