我正在使用GORM进行项目,根本没有任何Grails,并且在尝试执行findByX时遇到问题。例如,当我尝试
Country.findByName("Canada")
该项目没有编译,它给了我
Error:(80, 9) Groovyc: [Static type checking] - Cannot find matching method app.domain.location.Country#findByName(java.lang.String). Please check if the declared type is right and if the method exists.
即使字段名称存在。
但是,我可以在CountryService.groovy中通过以下方式定义findByName方法:
@Where({ name == countryName })
static Country findByName(String countryName){
Country.findAll().first()
}
但是我认为这根本不是一个好习惯。
总而言之,是否有依赖项,配置或执行Domain.findByX()之类的GORM查询所需的任何内容?还是无法单独使用GORM?
提前致谢。
最佳答案
您的问题不是GORM方法不存在(最终);而是这是因为它在编译时不存在,并且您似乎正在使用@CompileStatic
(或在默认位置配置了项目)。
从Grails文档中(该文档讨论了Gorm和CompileStatic):
https://docs.grails.org/latest/guide/staticTypeCheckingAndCompilation.html
One limitation of using CompileStatic is that when you use it you give up access to the power and flexibility offered by dynamic dispatch. For example, in Grails you would not be able to invoke a GORM dynamic finder from a class that is marked with CompileStatic because the compiler cannot verify that the dynamic finder method exists, because it doesn’t exist at compile time.
如果要使用GORM动态查找器,则需要使用这些查找器为方法/类关闭
@CompileStatic
。因此,要么删除@CompileStatic
批注,要么添加@CompileDynamic
其他相关:
关于grails - 独立使用GORM使用Domain.findBy [property]时遇到的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54039515/