2
votes

I recently inherited a Grails code base with a domain class called Name with (among others), the properties first and last to represent the first and last parts of a name, respectively. When writing a unit test which utilized this domain, I ran into some problems stemming from the names of these properties being the same as the first and last methods within Grails. Now, I can fix the problems by renaming the properties, but I was wondering if there is a way within Grails to use the property names first and last.

Namely, the error I was receiving was No signature of method: com.example.Name.first() is applicable for argument types: () values: [] Possible solutions: first(), first(java.lang.String), first(java.util.Map), list(), list(java.util.Map), print(java.lang.Object) when Grails attempts to apply a nullable: true constraint to the properties.

Here's the source of Name:

class Name {
    String first
    String middle
    String last
    static belongsTo = [person : Person]

    static constraints = {
        first(nullable:true)
        middle(nullable:true)
        last(nullable:true)
    }

    public static Name findOrCreate(String first, String middle, String last){
        def name
        name = Name.createCriteria().get{
            and{
                eq('first', first)
                eq('middle', middle)
                eq('last', last)
            }
        if(!name){
            name = new Name()
            name.first = first
            name.middle = middle
            name.last = last
        }       
        return name
    }

    static mapping = {
        cache true
    }

}
1
You should be using name.first to get the first name of a Name instance. Why should it clash with Name.first() in any way? - dmahapatro
In the constraints block, when Grails attempts to apply first(nullable:true), the exception noted above is thrown. - RandomMooCow
Your findOrCreate method is functionally identical to this method that's added by GORM to all domain classes grails.org/doc/latest/ref/Domain%20Classes/… - Dónal

1 Answers

7
votes

You say that this error happens in the constraints block. In that case you may be able to get it working with an explicit delegate., i.e.

static constraints = {
  delegate.first(nullable:true)
  // and similarly for last
}

to force the first to be treated as a call into the constraints DSL rather than to the static GORM method.