Converting Mutable to Immutable with Hibernate

2019-08-01 00:08发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-01 00:40

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

查看更多
登录 后发表回答