简体   繁体   English

Spring JPA,CrudRepository 的 save 方法是否立即提交到 DB?

[英]Spring JPA, does CrudRepository's save method commit to DB immediately?

By Default, Spring Data JPA has auto-commit disabled.默认情况下,Spring Data JPA 已禁用自动提交。
So if I am using/extending CrudRepository to save an object using save method, what is happening behind the scene??因此,如果我使用/扩展CrudRepository来使用save方法保存对象,那么幕后发生了什么? After saving the object to DB does spring jpa also commit the operation or not.将对象保存到数据库后,spring jpa 是否也提交了操作。
If it does not, how can i explicitly commit the operation?如果没有,我如何明确提交操作?

Edit following "Michal Drozd" comment: (The below is for JpaRepository not CrudRepository)编辑以下“Michal Drozd”评论:(以下适用于 JpaRepository 而不是 CrudRepository)
This article: Difference Between save() and saveAndFlush() in Spring Data JPA seems to indicate that for Spring Data JPA, auto-commit is false by default.这篇文章: Spring Data JPA 中 save() 和 saveAndFlush() 的区别似乎表明对于 Spring Data JPA,默认情况下自动提交为 false。

When we use the save() method, the data associated with the save operation will not be flushed to the DB unless and until an explicit call to flush() or commit() method is made.当我们使用 save() 方法时,与保存操作相关的数据不会被刷新到数据库中,除非并且直到显式调用了 flush() 或 commit() 方法。

save() method of CrudRepository is @Transactional itself. CrudRepository save()方法是@Transactional本身。 So if you call it not in context of another transaction it will create one and commit or rollback it depending on success or failure of persisting entity.因此,如果您不在另一个事务的上下文中调用它,它将创建一个并根据持久化实体的成功或失败提交或回滚它。

If Spring JPA autocommit is turned on ( spring.datasource.hikari.auto-commit=true ), then during database setup (during spring initilization) autocommit variable is set in database to true (for MySQL it is SET autocommit=1 ), it will not call commit for each SQL statement.如果 Spring JPA 自动提交被打开( spring.datasource.hikari.auto-commit=true ),那么在数据库设置期间(在 spring 初始化期间)自动提交变量在数据库中设置为 true(对于 MySQL,它是SET autocommit=1 ),它不会为每个 SQL 语句调用 commit。 If you want to use commit then you need transaction.如果要使用提交,则需要事务。 So either enable autocommit or work in transactions.所以要么启用自动提交,要么在事务中工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM