grails - 防止从Grails Controller 写入数据库

标签 grails

我有一个作为学习练习而编写的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/

相关文章:

javascript - 从列表中移除一个 li 的内容并删除该 li

grails - 如何限制grails中的关联大小?

grails - 使用MYSQL时Grails条件查询失败并出现语法错误

grails - 如何从服务方法中找到运行 Grails 应用程序的主机名?

grails - 我们可以在 g :select optionValue? 中有多个字段吗

grails - 将grails-2.3.2迁移到2.4.0和将JDK 1.7迁移到1.8时出错

chalice : data binding

jquery - Grails 远程函数 onSuccess 与 onComplete

grails - Grails不会节省服务

database - 无法将数据保存在 grails 中的数据库中