代码之家  ›  专栏  ›  技术社区  ›  Etibar - a tea bar

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

  •  2
  • Etibar - a tea bar  · 技术社区  · 8 年前

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

    @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    } }
    

    第二种是删除事务并保存而不刷新

     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    } }
    

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

    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    } }
    

    在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
    

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

    谁能解释一下 save with flush without flush 工作

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

    1 回复  |  直到 8 年前
        1
  •  4
  •   Kadi Laidoja    8 年前

    save() flush: true 不启动数据库连接

    save(flush: true) 立即在数据库级别启动事务。 所以打电话之后 第一次,您应该已经在MYSQL日志文件中看到了一些行,可能是这样的:

    Query    SET autocommit=0
    Query    insert into survey (version, brand ,...)
    

    保存(刷新:true) 第二次继续交易(没有再次启动,因此没有 COMMIT