tags:

views:

113

answers:

1

I'm attempting to add a method to a grails domain class, e.g.

class Item {

  String name

  String getReversedName() {
    name.reverse()
  }

}

When I attempt to load the application using grails console I get the following error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory':Invocation of init method failed; nested exception is org.hibernate.PropertyNotFoundException: Could not find a setter for property reversedName in class Item ... 18 more

It looks like Hibernate is interpreting getReversedName() as a getter for a property, however in this case it is a derived field and hence should not be persisted. Obviously in my actual code the business logic I'm exposing is more complex but it isn't relevant to this question. I want to be able to call item.reversedName in my code/gsps.

How can I provide property (getter) access to a method in a Grails domain class without Grails attempting to map it with Hibernate?

+5  A: 

I believe you have two choices:

1) Use def

def getReversedName() {
  name.reverse()
}

2) Add a transients declaration to the top of your domain object:

 static transients = [ 'reversedName' ] 

[edit] (I'd go with #1) (I'd go with #2) ;-)

tim_yates
IMO, 2 is a better option, because it expresses your intent more clearly.
Don
Thanks Tim, both options work. Not sure which one I prefer yet.
Richard Paul
I agree with Don. If it returns a String, say so. def is an alias for Object, so callers won't know what the type is without reading docs or your code. IMO def is way overused in Groovy and Grails. It's pretty trivial to add the transients list.
Burt Beckwith
@Richard -- If both Don and Burt say option #2 is the way forward, I'm changing my mind and going with that one too :)
tim_yates
Reading the grails docs I've seen the static style used commonly, e.g. static mappings etc. So this does seem to be the favourable approach. Thanks all for your input.
Richard Paul