在 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/