Converting Mutable to Immutable with Hibernate

邮差的信 提交于 2019-12-13 00:17:02

问题


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)


回答1:


you can use Pack.read( id ) to get

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.

see http://grails.org/doc/latest/ref/Domain%20Classes/read.html



来源:https://stackoverflow.com/questions/17582593/converting-mutable-to-immutable-with-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!