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

标签 hibernate grails groovy immutability

我正在使用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必须是不可变的实例)。

我的问题是:
  • 如何使用Groovy在Immutable中转换Mutable对象?

  • 要么
  • 有没有办法从Hibernate检索不可变实例?

  • 另一个选择是将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/

    相关文章:

    JAVA - 从共享存储访问文件而无需安装

    java - 属性 hibernate.connection.driver_class 2 未指定 JDBC 驱动程序类

    tomcat - 找不到根目录中的 Grails 文件

    Grails 3.x 和 Jenkins : Save BUILD_NUMBER and date when deploying

    grails - Grails从一个域读取到另一个域

    java - 如何从 gradle 任务运行 groovy 方法?

    groovy - JMockit - 期望中的模拟方法不返回结果

    java - JPA 乐观锁定规范是否支持根据客户端提供的版本进行验证

    java - 使用 Jackson 处理 @RequestBody 中的 Null 和 Default 值

    java - 在 Spring MVC 中处理多个页面