使用Grails中的聚合函数派生属性

时间:2013-10-03 16:30:42

标签: grails groovy gorm

我正在尝试根据包含的对象创建派生属性。

以下示例:

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了,但我的情况比没有复杂对象的公式稍微复杂一些。

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

  

由GrailsTagException引起:执行标记时出错:在第[23]行评估表达式[Generation.findAll()]时出错:无法执行查询; SQL [选择this_.id为id22_0_,this_.version为version22_0_,this_.line_id为line3_22_0_,this_.name为name22_0_,MAX(engines.productionEnd)为formula0_0_,MIN(engines.productionStart)为formula1_0_ from generation this_];嵌套异常是org.hibernate.exception.SQLGrammarException:无法执行查询

1 个答案:

答案 0 :(得分:3)

尝试它的另一种方法是创建一个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
    }

}