我正在尝试基于包含的对象创建派生属性。
示例如下:
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但我的情况比与复杂对象无关的公式稍微复杂一些。
您可以在上面的代码中找到的解决方案会导致错误::
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
最佳答案
另一种尝试方法是创建 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
}
}
关于grails - 在 Grails 中使用聚合函数派生属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19164445/