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

Viewed 10415

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.

2 Answers

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.

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.

Related