- Most queries you write fetch data (like
select). - Modifying queries are used to change data (like
updateordelete).
- You use
@Queryto write a custom update or delete query. - You must add
@Modifyingannotation to tell Spring Data JPA that this query changes data (not just reads it).
Example: Update firstname for users with a certain lastname
@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);- This query updates all users with the given lastname and sets their firstname.
- Returns an
intindicating how many rows were updated.
- When you run modifying queries, the EntityManager cache (which holds entities in memory) is not cleared automatically.
- This means if you still have loaded User entities in your current transaction, their state might be out of sync after the update.
- You can tell Spring to clear the cache automatically by:
@Modifying(clearAutomatically = true)- You can write derived delete methods without writing a query explicitly:
void deleteByRoleId(long roleId);- Or write a bulk delete with a custom query:
@Modifying
@Query("delete from User u where u.role.id = ?1")
void deleteInBulkByRoleId(long roleId);| Method | How it Works | Lifecycle Callbacks Invoked? | Performance |
|---|---|---|---|
deleteByRoleId(long roleId) |
Finds users with the role, deletes one-by-one | Yes | Slower, uses more memory because it loads entities into memory first |
deleteInBulkByRoleId(long roleId) |
Runs a single delete query on the database | No | Faster, less memory use, but no entity lifecycle events |
- Lifecycle callbacks like
@PreRemoveare only called if entities are loaded and deleted one by one. - Bulk deletes skip these callbacks.
- Use derived delete methods if you want lifecycle callbacks and don’t mind loading entities.
- Use bulk delete queries (
@Modifying @Query) when performance matters and you don’t need callbacks.
- Use
@Modifyingwith@Queryto write update or delete queries. - Add
clearAutomatically = trueif you want to clear EntityManager cache after update/delete. - Derived delete methods load entities and delete individually (trigger callbacks).
- Bulk delete queries run a direct delete in the database (better performance, no callbacks).