I have a Grails application and want to create filters for my domain class using named query.
I have domains Act and Status, StatusName is an Enum:

class Act {
    static hasMany = [status : Status]
}

class Status {
    Date setDate
    StatusName name
    static belongsTo = [act : Act]
}

I want to filter Acts which have their most recent Status's name equal to specific name.
For now I have this code in Act:

static namedQueries = {
    filterOnStatus { StatusName s ->
        status {
            order('setDate', 'desc')
            eq 'name', s
            // I need only first Status, with most recent setDate
            // among all Statuses of that Act
        }
    }
}

But this filter all Acts that have Status with specific name, not only with most recent. I tried to place maxResult 1 in query, but it seems not to work.
Any help would be appreciated.

EDIT: Problem was solved that way:

filteronStatus {
    createAlias('status', 's1')
    eq 's1.name', s
    eq 's1.setDate', new DetachedCriteria(Status).build {
        projections {
            max('setDate')
            eqProperty('act', 's1.act')
        }
    }
}
有帮助吗?

解决方案

see 'namedQueries' from Grails Doc

// get a single recent Act

def recentAct = Act.filterOnStatus(statusName).get()

ADD:

HQL

"select s1.act from Status as s1 \
            where s1.name = :statusName \
            and s1.setDate = (select max(s0.setDate) from s1.act.status s0)"

NamedQuery

listByStatus { statusName ->
            createAlias('status', 's1')
            eq 's1.name', statusName
            eq 's1.setDate', new DetachedCriteria(Status).build{ projections { max('setDate')} eqProperty('act','s1.act') }
        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top