使用getter风格方法名称将业务逻辑添加到域类 [英] Adding business logic to a domain class using a getter style method name
问题描述
class Item {
字符串名称
字符串getReversedName(){
name.reverse()
}
}
当我尝试使用grails控制台加载应用程序时,出现以下错误:
原因:org.springframework.beans.factory.BeanCreationException:创建名为'sessionFactory'的bean时出错:init方法的调用失败;嵌套的异常是org.hibernate.PropertyNotFoundException:无法在类Item
... 18中找到属性reversedName的setter
<看起来Hibernate将getReversedName()解释为属性的getter,但是在这种情况下,它是派生字段,因此不应该被持久化。很显然,在我的实际代码中,我公开的业务逻辑比较复杂,但与此问题无关。我希望能够在代码/ gsps中调用item.reversedName。
如何在不使用Grails的情况下为Grails域类中的方法提供属性(getter)访问试图用Hibernate映射它?
我相信你有两个选择:
)使用def
def getReversedName(){
name.reverse()
}
2)在你的域对象的顶部添加一个瞬态声明:
static transients = ['reversedName']
[edit] (我会去#1)(我会去#2); - )
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?
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) ;-)
这篇关于使用getter风格方法名称将业务逻辑添加到域类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!