0

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

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

    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]

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

4

2 回答 2

2

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

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])

希望能帮助到你!

于 2016-01-15T10:03:00.203 回答
1

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

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

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

于 2016-01-15T10:45:00.880 回答