我试图基于包含的对象创建派生的属性。

下面的例子:

class Generation {

    String name

    DateTime productionStart

    DateTime productionEnd

    static belongsTo = [line: Line]

    static hasMany = [bodyStyles: BodyStyle, engines: Engine, models: Model]

    static constraints = {
        line nullable: false
        name nullable: false, unique: ['line'], maxSize: 255, blank: false
    }

    static mapping = {
        // I've tried but this solution causes errors
        productionStart formula: 'MIN(engines.productionStart)'
        // I've tried but this solution causes errors
        productionEnd formula: 'MAX(engines.productionEnd)'
    }
}

class Engine {

    String name

    Integer horsePower

    DateTime productionStart

    DateTime productionEnd

    static belongsTo = [generation: Generation]

    static hasMany = [models: Model]

    static constraints = {
        generation nullable: false
        name nullable: false, unique: ['generation', 'horsePower'], maxSize: 255, blank: false
        horsePower nullable: false
        productionStart nullable: false
        productionEnd nullable: true
    }

    static mapping = {
        productionStart type: PersistentDateTime
        productionEnd type: PersistentDateTime
   }
}

我已经读过Derived Properties Documentation,但是我的情况比不与复杂对象关联的公式要复杂一些。

您可以在上面的代码中找到的解决方案将导致错误:

最佳答案

尝试它的另一种方法是创建一个getter而不是派生的属性:

class Generation {

    String name

    DateTime productionStart

    DateTime productionEnd

    static transients = ['productionStart','productionEnd']

    static belongsTo = [line: Line]

    static hasMany = [bodyStyles: BodyStyle, engines: Engine, models: Model]

    static constraints = {
        line nullable: false
        name nullable: false, unique: ['line'], maxSize: 255, blank: false
    }


    DateTime getProductionStart() {
      def datetime = Engine.createCriteria().get {
        eq('generation',this)
        projections {
          min('productionStart')
        }
      }

      return datetime

    }

    DateTime getProductionEnd() {
      def datetime = Engine.createCriteria().get {
        eq('generation',this)
        projections {
          max('productionEnd')
        }
      }

      return datetime
    }

}

10-08 13:23
查看更多