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
Difference between save and saveAndFlush in Spring 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 save
and saveAndFlush
.
I don't get the difference between these two. On calling save
also my changes are getting saved into database so what is the use of saveAndFlush
.
我遇到了两种方法save
和saveAndFlush
. 我不明白这两者之间的区别。在调用时,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 flush
or commit
commands are issued.
On saveAndFlush
,更改将在此命令中立即刷新到 DB。对于save
,这不一定是正确的,并且可能只保留在内存中,直到发出flush
或commit
命令。
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 commit
command for you if everything works out fine.
在您的情况下,您可能使用某种事务机制,commit
如果一切正常,它会为您发出命令。
回答by Ralf
Depending on the hibernate flush mode that you are using (AUTO
is the default) save
may or may not write your changes to the DB straight away. When you call saveAndFlush
you 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()
因为选择首先触发刷新的行为差异。请参阅文档。