The labs on this site need JavaScript to run. The same content is written out below.
Learn › JPA › Persistence context
Persistence context
When does JPA send SQL?
Why it exists — When you work with JDBC directly, every time you change an object's value you have to write and run an UPDATE statement, and if you read the same row twice, two queries are sent and two different objects are created. The persistence context manages the entities read during one transaction, one for each id, and compares them with their state when first read. It sends an UPDATE by itself for an entity whose value changed, and it does not go to the database when you look up the same entity by id again.
Where it's used today — In a service that uses Spring Data JPA, when a @Transactional method loads an entity and only changes a value, an UPDATE is sent at commit without calling save, and this behavior is the reason. When you insert or modify a lot of data at once, the number of managed entities keeps growing, so you call flush and clear from time to time, or use JdbcTemplate or a bulk UPDATE query instead.
JPA keeps entities in an in-memory space called the persistence context. It does not send SQL at the moment a line of code runs. It collects the SQL and sends it when it is needed.
Checked against real execution · The SQL of 6 scenarios was checked against Hibernate 7.4.5 and H2
Concepts in this lab
- Persistence context
- The logical space in JPA that holds and manages entities. Entities that you load or save are kept here, and JPA tracks the changes made to them and applies those changes to the database when the transaction ends. It usually shares its lifecycle with one transaction (in a web request with Open Session in View (OSIV) turned on, it lasts until the request ends). Features such as the first-level cache, dirty checking, and transactional write-behind work on top of it.
- First-level cache
- Where it's used today — It works without any extra configuration when you look up the same id again with em.find() or findById() within the same transaction. When you query with JPQL or a query method, the SQL goes to the database even for an entity that is already managed.
- The store inside the persistence context that keeps entities by identifier. If you load the same identifier again within the same transaction, it returns the stored entity without sending a query to the database. As a result, entities with the same identifier are always the same object within the same transaction. By default it disappears when the transaction ends (in a web request with Open Session in View (OSIV) turned on, it lasts until the request ends), so it is different from an application-wide cache.
- Dirty checking
- Where it's used today — It is used when you finish an update in a @Transactional service method by loading an entity and only changing its values. A change made outside a transaction, or a change to a detached entity, is not applied, so in that case you modify an entity that you loaded again inside a transaction.
- The feature that automatically runs UPDATE statements for changed entities. When the values of an entity managed by the persistence context change, JPA compares the entity with the state it first read at flush time (usually just before the commit), and it runs an UPDATE statement for each entity whose values differ. By default, Hibernate puts all columns in the UPDATE statement, not only the changed columns. To include only the changed columns, use @DynamicUpdate. So if you only change the values of an entity that you loaded, the change is applied to the database without calling a separate save method.
- Transactional write-behind and flush
- Why it exists — If SQL were sent right away every time an entity changed, then even changing the same row several times would send that many UPDATE statements, and every statement would make a trip to the database. Transactional write-behind delays the SQL until the flush, sends it once with the final state, and, depending on the settings, lets several statements be grouped into a JDBC batch.
- Where it's used today — In batch jobs that save many rows, you turn on hibernate.jdbc.batch_size to group INSERT statements (they are not grouped with the IDENTITY strategy). In tests, you send the SQL right away with em.flush() and em.clear() and read it back from the database to check.
- Transactional write-behind means that INSERT, UPDATE, and DELETE statements are not sent to the database right away. They are collected and sent together. However, for an entity whose primary key is generated with the IDENTITY strategy (such as AUTO_INCREMENT in MySQL), the INSERT runs immediately when you request the save, because the identifier must be obtained. A flush sends the collected changes to the database. It happens automatically just before the transaction commits and just before a JPQL query runs. A flush only sends SQL to the database. It does not commit the transaction.
- Entity
- A Java object that corresponds to a row of a database table. It is defined as a class annotated with @Entity and has an identifier (@Id). JPA tracks the state changes of these objects and runs the matching SQL.
Try these
- Default settings — Only the name is changed, yet an UPDATE is sent at commit (dirty checking).
- Without @Transactional — It is the same code, but no UPDATE is sent.
- Load the same member twice — The second load does not go to the database (first-level cache).
- Save: IDENTITY strategy — An INSERT is sent right away on every persist call.
- Save: SEQUENCE strategy — The INSERTs are collected and sent together at commit (transactional write-behind).
- JPQL query after a change — Even before the commit, an UPDATE is sent just before the JPQL query runs.
Running with the default settings
- Line 1: A SELECT reads member 1 and keeps it in the persistence context. The value at the time it was read, "Alice", is kept as the snapshot.
- Line 2: Only the name of the Java object was changed. No SQL goes to the database at this moment. Inside the persistence context, the current value (Bob) now differs from the snapshot (Alice).
- Line 3: The method ends without calling save.
- Method ends, commit: A flush happens just before the commit. JPA compares the current values of the managed entities with their snapshots, finds that member 1 has changed, builds an UPDATE, sends it to the database, and then commits. This is dirty checking.
Result of this run
- An UPDATE was sent even though no update method or save was called. For an entity managed by the persistence context, if you only change a value, JPA compares it with the snapshot at commit time and builds the SQL for you.
Code
// Only a method in the class body is shown (class declaration, field declarations, and imports omitted)
@Transactional
public void run() {
Member m = memberRepository.findById(1L).orElseThrow();
m.setName("Bob");
// The method ends without calling save()
} // the commit happens when the method ends
Assumptions of this model
This lab assumes that the code runs inside a single persistence context. For the sequence strategy, it simplifies the model to one sequence query per persist call. With the actual default setting (allocationSize 50), ids are fetched in blocks, so far fewer sequence queries are sent. In the "Without @Transactional" example, it assumes that the query method of a Spring Data repository runs in its own transaction and then ends. With the default open-in-view setting of Spring Boot, the entity may remain in the managed state, but there is still no commit, so no UPDATE is sent and the result is the same. All 6 scenarios were run on real Hibernate 7.4.5 with an H2 database, and the number of SQL statements sent, the time at which the write SQL was sent, and the values left in the DB were confirmed to match the screen (for the sequence strategy, they were run with allocationSize set to 1 to match the simplification on the screen).
Previous lab: What JPA solves · Next lab: The lifecycle of an entity