且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Hibernate将可变转换为不可变

更新时间:2023-10-27 10:45:10

您可以使用 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 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