7
votes

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
@MichalDrozd could you further bolster your case with any reference. I will greatly appreciate it as I can use the same reference to present to my peers. - user14198645
@joveny It's the other way round. Hibernate is built on top of JPA. JPA(Java Persistence API) is a specification while its popular implementations are Hibernate, EclipseLink,etc. - Ayush28
@Ayush28, I meant Spring Data JPA, not JPA as in the comment. ( I re-posted the comment). Thanks for pointing. So what I meant is Spring Data JPA is built on top of Hibernate while Hibernate is an implementation of JPA. - user14198645
@MichalDrozd, thanks. I googled for JDBC auto-commit mode and found this When a connection is created, it is in auto-commit mode. Ref -> Using Transactions. Similarly for Hibernate i found this : By default the autocommit value is false, therefore the transaction needs to be commited explicitly. Ref -> SOF. Since, Spring Data JPA is built on top of Hibernate, I thought it too has autocommit false. - user14198645
to be more precise - Spring Data JPA is built on top of JPA Provider - be it Hibernate or something else... hope so - user14198645

2 Answers

2
votes

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.

-1
votes

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.