Quick revision
The short answer
We write @Modifying(clearAutomatically = true) @Query("update User u set u.active = false where u.lastLogin < :cutoff") int deactivate(@Param("cutoff") Instant cutoff) and call it from a @Transactional service method; it returns the number of rows updated. The update runs directly in the database and bypasses the persistence context, so clearAutomatically clears that context afterwards and no stale User objects are reused, while flushAutomatically flushes pending changes before the update runs.
What to remember
In this answer, we wrote a @Modifying JPQL update that deactivates users whose last login is before a cutoff, returning the number of updated rows, and called it from a @Transactional service method because bulk statements require a transaction. We saw that the update bypasses the persistence context, so already loaded users become stale, and that clearAutomatically clears the context after the update while flushAutomatically flushes pending changes before it.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We write @Modifying(clearAutomatically = true) @Query("update User u set u.active = false where u.lastLogin < :cutoff") int deactivate(@Param("cutoff") Instant cutoff) and call it from a @Transactional service method; it returns the number of rows updated. The update runs directly in the database and bypasses the persistence context, so clearAutomatically clears that context afterwards and no stale User objects are reused, while flushAutomatically flushes pending changes before the update runs.
Why this question is asked
Deactivating dormant accounts is a typical housekeeping job: thousands of rows, one simple rule. Loading each user, changing a field and saving it would work, but it is slow and wasteful. A bulk update does it in one statement. Interviewers ask this question because bulk updates behave differently from normal entity changes, and the difference causes subtle bugs. In this answer, we will write the repository method, call it from a service, see what happens to the persistence context, and understand exactly what clearAutomatically and flushAutomatically do.
1A Quick Recap of Entity Updates Versus Bulk Updates
Normally we change data in JPA by loading an entity, calling a setter, and letting Hibernate write the change at flush time. Hibernate finds the change through dirty checking: it compares each managed entity with the snapshot it took when the entity was loaded, and generates an update for each one that differs.
A bulk update is a JPQL update statement. Hibernate translates it into one SQL update and sends it straight to the database. It does not load the rows, does not look at the persistence context, the set of entities the current transaction has loaded, and does not run per-entity logic. That is why it is fast, and also why it needs care.
| Load, set, save | Bulk JPQL update | |
|---|---|---|
| SQL statements for 10,000 users | 10,000 selects and updates (or batches) | 1 update |
| Persistence context | Kept in sync | Not touched |
Entity listeners and @Version | Applied | Bypassed |
| Return value | The saved entity | Number of rows updated |
2Writing the Repository Method
In Spring Data JPA, a @Query that changes data needs @Modifying, which tells Spring Data to call executeUpdate() instead of expecting a result list. The int return value is the number of rows the database updated.
Notice the query uses entity and field names, User and lastLogin, not table and column names. Hibernate maps them to the users table and the last_login column. If a user has a null lastLogin, the comparison is unknown in SQL, so that row is not updated; if never-logged-in users should also be deactivated, the query needs or u.lastLogin is null.
3Why It Needs a Transaction
JPA executes update and delete queries only inside an active transaction. Without one, Hibernate throws a TransactionRequiredException with a message about executing an update or delete query. Spring Data does not open a write transaction for the query methods we declare ourselves, so we annotate the calling service method with @Transactional, as above, or annotate the repository method.
Putting it on the service method is usually better, because the service defines the unit of work. If the cleanup also writes an audit record and that fails, both changes roll back together.
4The Stale Entity Problem
Because the update bypasses the persistence context, any User already loaded in the same transaction keeps its old state. Reading it again returns the cached object, not the row in the database.
There is a worse case. If the code later modifies that stale User, for example to update its email, dirty checking writes the whole entity back, depending on the mapping, and can set active back to true, undoing the bulk update for that row.
5What clearAutomatically and flushAutomatically Do
clearAutomatically = true tells Spring Data to call entityManager.clear() right after the update. Every managed entity is detached, so the next findById goes to the database and sees active = false. In the example above, again.isActive() then prints false.
But clearing has a catch: any change we made to entities and had not yet flushed is thrown away with them. That is what flushAutomatically = true is for. It calls entityManager.flush() before the update, so pending changes reach the database first. Hibernate usually flushes before a JPQL update anyway in its default flush mode, but setting the flag makes the intent explicit and safe regardless of flush settings. Using both together is a good default.
- flushAutomaticallypending entity changes are written first
- Run the bulk updateupdate users set active = false where last_login < ?
- Return the row countfor example 1834
- clearAutomaticallypersistence context cleared, entities detached
- Next readcomes from the database, so it is fresh
5 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Why not just loop over the users and call save?
For 2,000 users it works, but it loads every user, keeps them in memory, and sends an update per row, even with JDBC batching that is far more work than one statement. The loop does run entity listeners and versioning, so if auditing per row matters we either use the loop in batches or set the audit columns in the bulk statement.
Does clearAutomatically affect entities outside the transaction?
No. It clears the persistence context of the current EntityManager, which is bound to the current transaction. Other transactions have their own contexts. The second-level cache is separate: Hibernate invalidates the User cache region after a JPQL bulk update itself.
What if we need to know which users were deactivated?
A JPQL update only returns a count. We can select the ids first with the same condition and then update where id in those ids, inside the same transaction, or on PostgreSQL use a native update with a returning clause run as a query.
7Conclusion
In this answer, we wrote a @Modifying JPQL update that deactivates users whose last login is before a cutoff, returning the number of updated rows, and called it from a @Transactional service method because bulk statements require a transaction. We saw that the update bypasses the persistence context, so already loaded users become stale, and that clearAutomatically clears the context after the update while flushAutomatically flushes pending changes before it.
Open with
I would add a repository method with @Modifying(clearAutomatically = true, flushAutomatically = true) and @Query("update User u set u.active = false where u.lastLogin < :cutoff"), taking an Instant cutoff and returning int, which is the number of rows updated. @Modifying is what makes Spring Data call executeUpdate instead of expecting results.
Then, if they want more
I call it from a service method annotated with @Transactional, because JPA only runs update queries in a transaction and would otherwise throw TransactionRequiredException. The important part is that a bulk update goes straight to the database as one SQL statement.
It does not load users and it does not touch the persistence context, so any User loaded earlier in the same transaction still says active is true, and if I later modify it and it gets flushed, it could even overwrite the change. clearAutomatically calls clear on the EntityManager after the update, so the next read comes from the database. flushAutomatically calls flush before the update, so my own pending changes are written instead of being thrown away by the clear.
I would also mention that bulk updates skip entity listeners and @Version, so auditing has to be handled in the statement.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a Spring Data JPA bulk update that deactivates users who have not logged in since...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/901bf2f3c2/