hibernate - 覆盖隐式 getter 时 Grails 域类的行为异常

标签 hibernate grails groovy

考虑以下 grails 域类:

测试.groovy

package test

class Test {    
    Integer month
    Integer year
    String performancePeriod = ""

    static constraints = {      
        month(range:01..12, nullable:true)
        year(range:2010..2020, nullable:false)
        performancePeriod(nullable:true)        
    }

    String getPerformancePeriod() {
        if(month) {
            "${month?.toString().padLeft(2,'0')}.${year?.toString()}"
        }
        else {
            getYearStringFormat()
        }
    }

    String getPerformancePeriodDate(){
        return new GregorianCalendar(year, month, 1).time
    }

    String getJahrStringFormat() {
        year ? year.toString() : ""
    }

    String getMonatZweiStellig() {
        month? month.toString().padLeft(2,'0') : ""
    }   
}

它是遗留代码。我知道设计很糟糕,因为表示逻辑绑定(bind)到域对象。通过表示逻辑,我的意思是属性 performancePeriod ,其唯一目的是提供年份和日期的字符串格式以进行演示。

现在,生成 Controller 并搭建 View 。如果您创建一个新的 Test不设置记录performancePeriod , 该属性将使用方法 getPerformancePeriod 中给出的逻辑隐式设置.

我无法理解这种行为。我一开始就知道设计很糟糕,尤其是因为函数依赖 {year, month} -> performancePeriod , 但是什么时候 performancePeriod保存到数据库?为什么在我决定设置一个值之前我不能决定让它为空?

最佳答案

Why can't I decide to have it null until I decide to set a value?



你可以。当持久性引擎持久化您的对象时,它必须询问对象以检索特定属性的值。当引擎询问您的 performancePeriod 的值时您永远不会返回 null 的属性。无论您告诉它performancePeriod 的值,持久性引擎都会持久化。属性(property)是。您在域类中混淆了关注点,而您描述为有问题的行为是由此产生的结果。

由于几个原因,你写类(class)的方式很特别。 performancePeriod字段永远不会被用于任何事情。我不能从你的问题中确定,但可能是混淆的一部分是你没有区分字段的定义和属性的定义。

关于hibernate - 覆盖隐式 getter 时 Grails 域类的行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30977128/

相关文章:

java - 表中的更多名称属性

MySQL和Hibernate同时读写

grails - Grails审核日志记录插件onSave in UserRole

没有管理器的 Grails Spring Security Ldap

java - 1) Java 和 2) Groovy 会自动导入哪些包?

java - Hibernate JDBC 批量大小不起作用

java - HQL加入: Retrieve Object based on 2 joins (Path expected for join!)

html - 使用 g :select in grails 时如何设置选定值

字段之间关系的 Grails 域类约束

Grails[Groovy],如何获取一个类没有继承的所有方法的列表?