2013-10-03 53 views
2

我想根據包含的對象創建派生屬性。下面在Grails中使用聚合函數的派生屬性

例子:

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 
    } 
} 

我readed Derived Properties Documentation,但我的情況是一點點比不了複雜的對象相關的公式比較複雜。

,你可以找到在上述結果的代碼中的錯誤::

Caused by GrailsTagException: Error executing tag : Error evaluating expression [Generation.findAll()] on line [23]: could not execute query; SQL [select this_.id as id22_0_, this_.version as version22_0_, this_.line_id as line3_22_0_, this_.name as name22_0_, MAX(engines.productionEnd) as formula0_0_, MIN(engines.productionStart) as formula1_0_ from generation this_]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query

回答

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 
    } 

}