禁止从Grails控制器写入数据库

时间:2019-06-20 15:15:06

标签: grails

我有一个Grails小项目正在编写,作为学习练习。它从表单中收集一些用户输入(例如,输入两个数字以相加),然后调用服务来处理该数据(例如,将两个数字相加),最后将结果显示在另一页上。

当我打开SQL日志记录时,我注意到在调用控制器内部的service方法之前,用户输入的数据已保存到数据库中。

如何防止这种情况?我希望在对service方法的调用完成并且没有错误之后,一次写入数据库。

从控制器代码中保存方法:

 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()])
      }
 }

指针或帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

调用.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()])
      }
 }