gpt4 book ai didi

grails - 覆盖 addTo 和 removeFrom 以监听 Grails 中属性的变化

转载 作者:行者123 更新时间:2023-12-01 14:46:10 24 4
gpt4 key购买 nike

我是 Grails 的新手,我需要在“有很多”属性发生变化时进行一些计算,我认为最好的地方是在属性的 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

谢谢

最佳答案

当您处理域对象时,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 允许将服务注入(inject)域 (POGO)。

关于grails - 覆盖 addTo 和 removeFrom 以监听 Grails 中属性的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23315480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com