Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JPA and Hibernate automatically update database without transaction begin and commit

In JPA, if I try to update a managed object using setter and getter method without using transaction begin and commit, does JPA automatically update the database ( not immediately but later) considering FlushType is in AUTO.

like image 223
Samuel Gebretnsae Avatar asked May 26 '26 08:05

Samuel Gebretnsae


1 Answers

In JPA, the entity state transitions are not automatically synchronized with the database. If the entity is attached to the persistence context, then at flush-time, the automatic dirty checking mechanism translates object state changes into DML statements.

But that requires the entity to be managed by the persistence context, as otherwise, the dirty checking mechanism will not trigger.

Although the JPA specification requires only entity state transitions to be wrapped in a logical transaction:

  • persist
  • merge
  • remove

You should ALWAYS use transaction, even when only reading data.

If you don't explicitly use transactions when reading data, then you fall back to auto-commit mode, putting additional pressure on the connection pooling mechanism, and ending up with one database transaction per query.

like image 125
Vlad Mihalcea Avatar answered Jun 01 '26 23:06

Vlad Mihalcea