Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA: Should the Save() method commit data to the database?

I am using Spring data for my project, I am using a Standard Repository that extends CRUD Repository.

My code is working as expected, however when I call repository.save() the database is not altered?

Do I also need to then call a commit after this in order to alter the Database? Or should the repository.save() method be altering the database automatically?

like image 788
java123999 Avatar asked Feb 26 '16 12:02

java123999


People also ask

Does JPA save commit?

By Default, Spring Data JPA has auto-commit disabled.

What does save method do in JPA repository?

Spring Data JPA CrudRepository - save() Method As the name depicts, the save() method allows us to save an entity to the DB. It belongs to the CrudRepository interface defined by Spring Data.

Which method can be used to store records in a database in JPA?

In JPA, we can easily insert data into database through entities. The EntityManager provides persist() method to insert records.

Does save and flush commit?

No. It doesn't flush data directly to a database until and unless we explicitly call flush and commit method. It's flush directly flush data to a database. It doesn't flush data directly to a database, therefore, changes will not be visible outside the transaction unless we explicitly call commit() in this transaction.


1 Answers

When your application runs, the Entity Manager associated with the thread keeps control of modified or added objects, the save() method just do this, it's a mark that says: "this should be saved in the database".

The database DML (insert,update,delete) is not sent to the database while you save things, it's done at the end just before commit, it's delayed to the last moment.

It's possible the send the DML to the database anytime you like using the Entity Manager's flush() method, in fact you can debug the database log and see your queries going through, but this changes to the database will only be visible within your DB connection until the commit is issued; commit() is a method of the transaction associated to the Entity Manager.

In some frameworks like play 1.4.x the commits is issued after the response view is correctly parsed and rendered.

like image 126
Hans Poo Avatar answered Oct 13 '22 14:10

Hans Poo