grails - Gorm finder 的奇怪行为

标签 grails grails-orm

在 Controller 中我有这个查找器

User.findByEmail('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="473322343307332234336924282a" rel="noreferrer noopener nofollow">[email protected]</a>')

并且有效。

即使我写也能工作

User.findByEmail(null)

但是如果我写

User.findByEmail(session.email)

并且 session.email 未定义(因此为 null),它会抛出异常

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

这种行为正确吗?

如果我评估“session.email”,它会给我空,所以我认为它必须像我写入时一样工作 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: []

最佳答案

您无法使用标准 findBySomething 动态查找器来搜索 null 值,您需要使用 findBySomethingIsNull 版本。尝试一下

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

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

WHERE something = null

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

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

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

然后在 Controller 中使用User.byOptEmail(session.email)

关于grails - Gorm finder 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13760078/

相关文章:

grails - Gorm一对一和一对多

grails - 找出哪个Quartz触发器触发了作业

hibernate - 在 Grails 中,如何访问域类静态方法内的 hibernate session ?

Grails 数据库迁移插件

grails - 使用 GORM 根据子表中的列进行排序?

hibernate - 如何在条件中使用 'in' 来查询子对象?

oracle - 将 Oracle 数据库连接到 Grails 3

grails - 如何实现软删除

grails - Grails 中的最大值和偏移量?

hibernate - 使用 Gorm 查询列子集