Grails .save(flush: true) 与 .save() 的行为相同

Eti*_*nov 2 grails groovy hql transactional

我们一直在测试一种不同的储蓄方式。然而,结果并不像我们预期的那样。我们有创建调查的方法,每个调查都有多个问题。我们测试了几个案例,它们都以相同的方式提交查询。

@Transactional class Service {
      Survey createNewSurvey(NewSurveyCommand command) {
       Survey survey = new Survey()
       survey.properties[] = command.properties
       survey.save(flush: true, failOnError: true)  //save survey and flush
       for (NewQuestionCommand questionCommand : command.questions) {
           Question question = new Question()
           question.properties[] = questionCommand.properties
           question.save(flush: true, failOnError: true)  // save each questions and flush
       }
       return survey    } }
Run Code Online (Sandbox Code Playgroud)

第二个删除事务性并保存而不刷新

 class Service {
      Survey createNewSurvey(NewSurveyCommand command) {
       Survey survey = new Survey()
       survey.properties[] = command.properties
       survey.save()  //save survey and flush
       for (NewQuestionCommand questionCommand : command.questions) {
           Question question = new Question()
           question.properties[] = questionCommand.properties
           question.save()  // save each questions and flush
       }
       return survey    } }
Run Code Online (Sandbox Code Playgroud)

第三次和第四次,一次有事务性,一次没有事务性。

class Service {
          Survey createNewSurvey(NewSurveyCommand command) {
           Survey survey = new Survey()
           survey.properties[] = command.properties
           survey.save()  //save survey and flush
           for (NewQuestionCommand questionCommand : command.questions) {
               Question question = new Question()
               question.properties[] = questionCommand.properties
              survey.addToQuestions()
    }
           survey.save(flush: true, failOnError: true)
           return survey    } }
Run Code Online (Sandbox Code Playgroud)

最后,从 MySQL 日志中,我们检查到无论我们做了什么,所有插入都发生在一次提交内。

    Query    SET autocommit=0
    Query    insert into survey (version, brand ,...)
    Query    insert into question (version,..d)
    Query    insert into question (version,..d)
    Query    commit
    Query    SET autocommit=1
Run Code Online (Sandbox Code Playgroud)

最后我们没有看到 .save(flush: true, failureOnError: true)、save() (有或没有事务性)之间有任何区别。

有人能解释一下是如何save with flush工作without flush的吗?

Grails 文档说,flush(可选)- 当设置为 true 时,会刷新持久性上下文,立即持久化对象。然而,在我们的案例中,我们看到,它并没有像医生所说的那样发生。还是我理解错了?

小智 5

save()withoutflush: true 不启动数据库连接。调用 save() 后,数据仅保留在 Hibernate 会话中。因此,在您的情况下,您不会在 MYSQL 日志文件中找到任何相关行。

save(flush: true) 立即在数据库级别启动事务。save(flush: true)因此,在第一次 调用后,您应该已经在 MYSQL 日志文件中看到一些行,可能类似于:

Query    SET autocommit=0
Query    insert into survey (version, brand ,...)
Run Code Online (Sandbox Code Playgroud)

第二次调用后,save(flush: true)事务将在数据库级别继续(不会再次启动,因此COMMIT两次保存之间不会发生)。您还可以看到添加到 MYSQL 日志文件中的行。