我是Grails的新手,我需要在" has-many"属性更改,我认为最好的地方是在属性的setter中,假设我的属性是addTo和removeFrom方法中应该最好的列表,我试图覆盖它们但没有'工作。
这是最好的方法吗?我的代码出了什么问题?
以下是代码:
Cicle.groovy
class Cicle {
String machine
int cicleValue
static hasMany = [measurements:Measurement]
static constraints = {
machine blank:false
cicleValue nullable:false
}
public void addToMeasurements(Measurement measurement){
super.addToMeasurements(measurement)
updateCalculations()
}
public void updateCalculations(){
int sumCicles = 0
measurements.each{ measurement ->
sumCicles += measurement.cicleValue
}
cicleValue = sumCicles / measurements.size()
this.save(failOnError: true)
}
}
这是我得到的例外:
No signature of method: com.rpc.mock.app.Cicle.addToMeasurements() is applicable for argument types: (com.rpc.mock.app.Measurement) values: [com.rpc.mock.app.Measurement : (unsaved)]
Possible solutions: addToMeasurements(com.rpc.mock.app.Measurement), addToMeasurements(java.lang.Object), getMeasurements(). Stacktrace follows:
Message: No signature of method: com.rpc.mock.app.Cicle.addToMeasurements() is applicable for argument types: (com.rpc.mock.app.Measurement) values: [com.rpc.mock.app.Measurement : (unsaved)]
Possible solutions: addToMeasurements(com.rpc.mock.app.Measurement), addToMeasurements(java.lang.Object), getMeasurements()
Line | Method
->> 16 | addToMeasurements in com.rpc.mock.app.Cicle
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 43 | $tt__save in com.rpc.mock.app.MeasurementController
| 200 | doFilter . . . . in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1145 | runWorker . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run . . . . . . . in java.lang.Thread
由于
答案 0 :(得分:0)
当你正在处理域对象时,GORM支持将事件注册为在发生某些事件时被触发的方法,例如删除,插入和更新:
beforeInsert - Executed before an object is initially persisted to the database
beforeUpdate - Executed before an object is updated
beforeDelete - Executed before an object is deleted
beforeValidate - Executed before an object is validated
afterInsert - Executed after an object is persisted to the database
afterUpdate - Executed after an object has been updated
afterDelete - Executed after an object has been deleted
onLoad - Executed when an object is loaded from the database
然后,您可以在域对象中添加updateCalculations()
,如下所示:
static constraints = {
machine blank:false
cicleValue nullable:false
}
def beforeUpdate() { updateCalculations() }
作为一般的优秀设计实践,最好将逻辑实现保留在域对象之外,Grails允许将服务注入域(POGO)。