Transient property in Grails domain

时间秒杀一切 提交于 2020-01-14 08:52:47

问题


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!


回答1:


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



回答2:


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"
        }
    }
}


来源:https://stackoverflow.com/questions/5388645/transient-property-in-grails-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!