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

huangapple go评论75阅读模式
英文:

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

问题

默认情况下,Spring Data JPA 已禁用自动提交。

因此,如果我正在使用/扩展 CrudRepository,使用 save 方法保存一个对象,幕后会发生什么呢?在将对象保存到数据库后,Spring JPA 是否也会提交操作呢?

如果不会,我如何显式地提交操作呢?

根据 "Michal Drozd" 的评论进行编辑:(以下内容适用于 JpaRepository 而不是 CrudRepository)

这篇文章:Spring Data JPA 中 save() 方法与 saveAndFlush() 方法的区别 似乎表明,对于 Spring Data JPA,默认情况下自动提交是禁用的。

> 当我们使用 save() 方法时,与保存操作相关的数据不会被刷新到数据库,除非显式调用 flush() 或 commit() 方法。

英文:

By Default, Spring Data JPA has auto-commit disabled.
So if I am using/extending CrudRepository to save an object using save method, what is happening behind the scene?? After saving the object to DB does spring jpa also commit the operation or not.
If it does not, how can i explicitly commit the operation?

Edit following "Michal Drozd" comment: (The below is for JpaRepository not 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.

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

答案1

得分: 2

如果启用了Spring JPA的自动提交(spring.datasource.hikari.auto-commit=true),那么在数据库设置过程中(在Spring初始化期间),会将数据库的自动提交变量设置为true(对于MySQL来说是SET autocommit=1),它不会为每个SQL语句调用提交操作。
如果你想要使用提交操作,那么你就需要使用事务。因此,要么启用自动提交,要么使用事务来工作。

英文:

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.
If you want to use commit then you need transaction. So either enable autocommit or work in transactions.

答案2

得分: 2

CrudRepositorysave()方法本身就是带有@Transactional注解的。因此,如果您在没有另一个事务上下文的情况下调用它,它将创建一个事务,并根据实体持久化的成功或失败进行提交或回滚。

英文:

save() method of CrudRepository is @Transactional itself. 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.

huangapple
  • 本文由 发表于 2020年10月1日 16:50:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/64151939.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定