Java Spring数据jpa中save和saveAndFlush的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21203875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:18:15  来源:igfitidea点击:

Difference between save and saveAndFlush in Spring data jpa

javaspringhibernatejpaspring-data-jpa

提问by Anand

I am trying to learn spring data JPA by testing some CRUD operation via JpaRepository.

我正在尝试通过测试一些 CRUD 操作来学习 spring 数据 JPA JpaRepository

I came across two methods saveand saveAndFlush. I don't get the difference between these two. On calling savealso my changes are getting saved into database so what is the use of saveAndFlush.

我遇到了两种方法savesaveAndFlush. 我不明白这两者之间的区别。在调用时,save我的更改也被保存到数据库中,那么saveAndFlush.

回答by user1918305

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flushor commitcommands are issued.

On saveAndFlush,更改将在此命令中立即刷新到 DB。对于save,这不一定是正确的,并且可能只保留在内存中,直到发出flushcommit命令。

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won'tbe visible to the outside transactions until the commit in this transaction.

但是请注意,即使您刷新事务中的更改并且不提交它们,在此事务中提交之前,这些更改仍然不会对外部事务可见。

In your case, you probably use some sort of transactions mechanism, which issues commitcommand for you if everything works out fine.

在您的情况下,您可能使用某种事务机制,commit如果一切正常,它会为您发出命令。

回答by Ralf

Depending on the hibernate flush mode that you are using (AUTOis the default) savemay or may not write your changes to the DB straight away. When you call saveAndFlushyou are enforcing the synchronization of your model state with the DB.

根据您使用的休眠刷新模式(AUTO默认值)save可能会也可能不会立即将您的更改写入数据库。当您打电话时,saveAndFlush您正在强制您的模型状态与数据库同步。

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save()and saveAndFlush()because the select triggers a flush first. See the documention.

如果您使用刷新模式 AUTO 并且您正在使用您的应用程序首先保存然后再次选择数据,您将看不到save()saveAndFlush()因为选择首先触发刷新的行为差异。请参阅文档