hibernate - Grails在命名查询中使用继承的属性

标签 hibernate grails gorm named-query

我想在派生实例的命名查询中使用继承的属性,以便可以提供自定义类型的结果。我收到一个错误。

package com.example

class Ticket {
    // User is defined elsewhere
    static belongsTo = [user : User]
    String idNumber
}

class SeasonTicket extends Ticket {

    // some custom properties go here

    static namedQueries = {
        locateOrderedSeasonTicketsByUser { user ->
            // all derived instances are in the same table, hence return only the correct derived instances
            eq("class", "com.example.SeasonTicket")

            // return a match on user
            user {
                idEq(user.id)
            }

            // implement custom order
            order "customProperty"
        }
    } << Ticket.namedQueries
}

最后一行允许使用基类中定义的所有继承的命名查询。

运行调用的集成测试时,出现以下错误:
SeasonTicket.locateOrderedSeasonTicketsByUser(someUserInstance)

No signature of method: com.example.User.call() is applicable for argument types: (com.example.SeasonTicket$__clinit__closure2_closure3_closure4) values: [com.example.SeasonTicket$__clinit__closure2_closure3_closure4@31ee7d7a] Possible solutions: wait(), last(), save(), any(), getAll(), wait(long)



集成测试是我第一次尝试进行简单的测试:
void "SeasonTicket.locateOrderedSeasonTicketsByUser finds an object"() {
    given:
    def seasonTicket = new SeasonTicket()
    def user = new User()       
    user.addToSeasonTickets(seasonTicket)
    user.save(flush: true, failOnError: true)

    expect: "we can find one season ticket"
    SeasonTicket.locateOrderedSeasonTicketsByUser(user).list().size() == 1
}

似乎未识别基类内的用户字段。请问我做错了什么?

最佳答案

您的本地参数user和类属性'user'之间存在命名冲突。

这部分条件

user {
    idEq(user.id)
}

会尝试在您不存在的本地参数user上调用一个方法,而不是使用userTicket属性来建立查询。

重命名namedQuery locateOrderedSeasonTicketsByUser的参数。

关于hibernate - Grails在命名查询中使用继承的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28188998/

相关文章:

sql - 如何从数据库 grails 重新加载域类的实例?

grails - 如何防止双向关联的级联删除?

spring - Spring 存储库中 EntityManager 注入(inject)时出现 java.lang.NullPointerException

grails - 执行<g:render/> Grails 3.0.5时出错

database - 使用Hibernate从Grails中的列查询数据库值

java - 如何在java项目中使用任务更改或替换gradle版本?

validation - Grails域对象在验证期间意外保存

grails - Grails查询,如何获取结果中的特定字段?

java - Hibernate setMaxResults 分页

java - Hibernate 方言 + datediff 函数