我有一个作为学习练习而编写的Grails小项目。它从表单收集一些用户输入(例如,输入两个数字相加),然后调用服务来处理该数据(例如,将两个数字相加),最后在另一个页面上显示结果。
当我打开SQL日志记录时,我注意到在调用 Controller 内部的service方法之前,用户输入的数据已保存到数据库中。
我该如何预防?我希望在对service方法的调用完成并且没有错误之后,一次写入数据库。
从 Controller 代码保存方法:
def save() {
def myInstance = new myDomainClass(params)
myInstance.sessionId = session.id
myService argh = new myService()
// wtf does this do?
if (!myInstance.save(flush: true)) {
render(view: "create", model: [myInstance: myInstance])
return
}
// Execute the api and process the results. what is writing the user input to the database before this call?!?!?!?!
def results1 = argh.executeApi(myInstance)
// if the results are null throw an error
if (results1 == null) {
flash.message = message(code: 'api.null.error')
render(view: "create", model: [apiInstance: apiInstance])
return
} else {
forward(action: "list", id: 2, model: [apiInstanceList: Api.list(params), apiInstanceTotal: Api.count()])
}
}
指针或帮助表示赞赏。
最佳答案
此时,调用.save(flush:true)
将自动将myInstance实例保存到数据库中。您将需要将.save(flush:true)
移至service方法之后,并且由于您说过要确保没有错误,因此需要将其添加到条件中:
def save() {
def myInstance = new myDomainClass(params)
myInstance.sessionId = session.id
myService argh = new myService()
// Execute the api and process the results. what is writing the user input to the database before this call?!?!?!?!
def results1 = argh.executeApi(myInstance)
// if the results are null throw an error
if (results1 == null) {
flash.message = message(code: 'api.null.error')
render(view: "create", model: [apiInstance: apiInstance])
return
} else {
// save here when you know there are no errors
if (!myInstance.save(flush: true)) {
render(view: "create", model: [myInstance: myInstance])
return
}
forward(action: "list", id: 2, model: [apiInstanceList: Api.list(params), apiInstanceTotal: Api.count()])
}
}
关于grails - 防止从Grails Controller 写入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689072/