Transient property in Grails domain
Asked Answered
F

2

6

I have a Grails domain called People, and I want to check that each People has childs or not. Childs are other People objects. Here is my domain structure:

class People implements Serializable {

    static constraints = {
        name (nullable : false, unique : true)
        createdBy (nullable : false)
        creationDate (nullable : false)
    }

    static transients = ['hasChild']

    static mapping = {
        table 'PEOPLE'
        id generator: 'sequence', params : [sequence : 'SEQ_PK_ID']
        columns {
            id column : 'APEOPLE_ID'
            parentPeople column : 'PARENT_PEOPLE_ID'
        }
        parentPeople lazy : false
    }

    People parentPeople
    String name
    String description

    Boolean hasChild() {
        def childPeoples = People.createCriteria().count { 
            eq ('parentPeople', People) 
        }
        return (childPeoples > 0)
    }
}

But I cannot call people.hasChild() at anywhere. Could you please helpe me on this? Thank you so much!

Florence answered 22/3, 2011 at 8:40 Comment(0)
A
4

It's because in eq ('parentPeople', People), Grails can't understand what "People" is (it's a class). You should replace "People" by this. For example:

static transients = ["children"]

    def getChildren() {
        def childPeoples = People.findAllByParentPeople(this, [sort:'id',order:'asc'])
    }
Allina answered 22/3, 2011 at 9:29 Comment(1)
Can you perform a setter as well?Switzer
M
0

Another way to get the same result is to use Named Queries. It seems more concise and was created specifically for this purpose. I also like it because it fits the pattern of static declarations in a domain model and it's essentially a criteria, which I use throughout my applications. Declaring a transient then writing a closure seems a bit of a work-around when you can declare named queries ... just my opinion.

Try something like this:

static namedQueries = {
    getChildren {
        projections {
            count "parentPeople"
        }
    }
}
Miculek answered 11/6, 2014 at 2:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.