我们一直在测试一种不同的储蓄方式。然而,结果并不像我们预期的那样。我们有创建调查的方法,每次调查都有多个问题。我们测试了几个案例,它们都以相同的方式提交了查询。
@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 } }第3和第4次,一次是事务性的,一次是没有事务性的。
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( failOnError: true、failOnError: true)、save() (有或没有事务处理)之间的任何区别。
有人能解释一下save with flush和without flush是如何工作的吗?
Grails医生说刷新(可选)--当设置为true时,会刷新持久性上下文,然后立即持久化对象。然而,在我们的案例中,它并没有像医生所说的那样发生。还是我误会了?
发布于 2017-07-26 07:35:36
没有save()的flush: true 不会启动数据库连接。调用save()之后,数据仅在Hibernate会话中持久化。因此,在您的例子中,您不会在MYSQL日志文件中找到任何相关的行。
save(flush: true) 立即在数据库级别启动事务。因此,在第一次调用save(flush: true)之后,您应该已经在MYSQL日志文件中看到了一些行,可能如下:
Query SET autocommit=0
Query insert into survey (version, brand ,...)在第二次调用save(flush: true)之后,事务将在数据库级别上继续进行(没有再次启动,因此在两个保存之间不会发生COMMIT )。您还可以看到添加到MYSQL日志文件中的行。
https://stackoverflow.com/questions/45302963
复制相似问题