Grails HQL命名参数不起作用

时间:2016-01-15 06:52:31

标签: grails hql grails-3.0.9

平台 | 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]

有人可以告诉我我犯的错误吗?位置参数似乎只是工作,但传递一个命名参数的映射导致这个奇怪的错误

2 个答案:

答案 0 :(得分:2)

你正在制作大错字,因为在命名查询的情况下我们传递map not list。请参阅以下代码:

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

希望它有所帮助!

答案 1 :(得分:1)

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

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

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