我正在使用Grails,并且具有以下域类:
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()
}
}
要出售一个Pack,我首先需要发布它,然后使用publish方法来发布Pack。
发布后,Pack不能更改(即发布后,Pack必须是不可变的实例)。
我的问题是:
要么
另一个选择是将canEdit()方法与Hibernate事件(beforeUpdate和beforeDelete)结合使用。如果canEdit()== false,那么我可以在beforeDelete或beforeUpdate中抛出RuntimeException。是一个好的解决方案?
观察:我认为Ruby中的Frozen方法完全可以满足我的需求。 (http://rubylearning.com/satishtalim/mutable_and_immutable_objects.html)
最佳答案
您可以使用Pack.read( id )
获取
an 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.
见http://grails.org/doc/latest/ref/Domain%20Classes/read.html
关于hibernate - 使用Hibernate将可变转换为不可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17582593/