Grails HQL 命名参数不起作用

Grails HQL Named Parameters Not Working

平台 | Grails 版本:3.0.7 | Groovy版本:2.4.4 | JVM 版本:1.8.0_51

我似乎无法在 Grails HQL 查询中使用命名参数。以下作品(在 Grails 服务内 class)。

    def query = 'from Event event ' +
                'where event.eventName like ? ' +
                'or event.address.town like ?'
    def results = Event.executeQuery(query, ["%London%", "%London%"], [offset: 5, max: 5])

但是,以下方法不起作用:

    def query = 'from Event event ' +
                'where event.eventName like :searchEventName ' +
                'or event.address.town like :searchTownName'
    def results = Event.executeQuery(query, [searchEventName, "%London%", searchTownName, "%London%"], [offset: 5, max: 5])

显示的错误是:

Class
groovy.lang.MissingPropertyException
Message
null
Caused by
No such property: searchEventName for class: com.mchq.event.SearchService

与我认为正确的相反,我然后声明属性...

    def searchEventName, searchTownName
    def query = 'from Event event ' +
                'where event.eventName like :searchEventName ' +
                'or event.address.town like :searchTownName'
    def results = Event.executeQuery(query, [searchEventName, "%London%", searchTownName, "%London%"], [offset: 5, max: 5])

并且报告的错误是:

Class
java.lang.IllegalArgumentException
Message
null
Caused by
No positional parameters in query: from Event event where event.eventName like :searchEventName or event.address.town like :searchTownName

作为最后一项测试,我尝试了以下删除变量声明和命名参数列表的操作。

    def query = 'from Event event ' +
                'where event.eventName like :searchEventName ' +
                'or event.address.town like :searchTownName'
    def results = Event.executeQuery(query, [offset: 5, max: 5])

很正确,消息返回为:

Class
org.hibernate.QueryException
Message
null
Caused by
Not all named parameters have been set: [searchEventName, searchTownName] [from Event event where event.eventName like :searchEventName or event.address.town like :searchTownName]

谁能告诉我我犯的错误?位置参数似乎只是在查找但传递了一个命名参数映射导致了这个奇怪的错误

你犯了很大的错字,因为在命名查询的情况下,我们传递的是地图而不是列表。请参阅下面的代码:

def query = 'from Event event ' +
                'where event.eventName like :searchEventName ' +
                'or event.address.town like :searchTownName'
    def results = Event.executeQuery(query, [searchEventName: "%London%", searchTownName: "%London%"], [offset: 5, max: 5])

希望对您有所帮助!

你传递参数的方式是错误的。 [searchEventName, "%London%", searchTownName, "%London%"] 是 groovy 中的列表。

您需要将它们指定为地图。地图定义为 [key1:value1, key2:value2].

所以正确的参数传递方式应该是[searchEventName: "%London%", searchTownName: "%London%"]