使用Hibernate将可变转换为不可变 [英] Converting Mutable to Immutable with Hibernate
问题描述
类包{
字符串代码
发布日期日期
//其他几个属性(包括集合hasMany)....
def isPublished(){
return publishedDate!= null $
$ b def publish(){
publishedDate = new Date()
}
def canEdit(){
return !isPublished()
}
}
发布它并且我使用发布方法来发布一个包。
发布后,一个包不能改变(即发布后,一个包需要是一个不可变的实例) 。
我的问题是:
或
- 有没有办法从Hibernate中检索一个不可变的实例?另一个选择是使用canEdit()方法结合Hibernate事件(beforeUpdate和beforeDelete )。如果canEdit()== false,那么我可以在beforeDelete或beforeUpdate中引发RuntimeException。是一个很好的解决方案吗?
Obs .:我认为Ruby中的冻结方法正是我所需要的。 ( http://rubylearning.com/satishtalim/mutable_and_immutable_objects.html )
解决方案您可以使用
Pack.read(id)
来获得
处于只读状态的指定标识的域类实例。如果具有指定id的行不存在,则返回null。
请参阅 http://grails.org/doc/latest/ref/Domain%20Classes/read.html
I'm using Grails and I have the following domain class:
class Pack { String code Date publishedDate //several other properties (including collections hasMany).... def isPublished() { return publishedDate != null } def publish() { publishedDate = new Date() } def canEdit() { return !isPublished() } }
To sell a Pack I first need publish it and I use the publish method to publicate a Pack.
After published, a Pack cannot be changed (i.e. after published, a Pack need to be a immutable instance).
My question is:
- How to transform a Mutable object in Immutable using Groovy?
or
- Is there a way to retrieve a Immutable instance from Hibernate?
Another option is to use the canEdit() method combined with the Hibernate events (beforeUpdate and beforeDelete). If canEdit() == false then I can throw a RuntimeException inside the beforeDelete or beforeUpdate. Is a good solution?
Obs.: I think that the freeze method in Ruby does exactly what I need. (http://rubylearning.com/satishtalim/mutable_and_immutable_objects.html)
解决方案you can use
Pack.read( id )
to getan instance of the domain class for the specified id in a read-only state. null is returned if the row with the specified id doesn't exist.
see http://grails.org/doc/latest/ref/Domain%20Classes/read.html
这篇关于使用Hibernate将可变转换为不可变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!