@Modifying update and delete queries
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A sale starts and a whole category must be hidden, or every book's price rises 10% before the new semester. Loading thousands of products into Java just to change one field is slow and sends one UPDATE per row.
@Modifying @Query update returning the row count
@Modifying is an annotation that marks a @Query as an UPDATE or DELETE, so Spring Data runs it with executeUpdate(). The method returns the number of rows touched (int or long), or void.
Hiding a whole category means one statement, not one per product. Watch one UPDATE change three mobiles at once.
Example 1 · A bulk UPDATE that returns the row count
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// src/main/java/com/shoplite/product/ProductRepository.java@Modifying@Query("update Product p set p.active = false where p.categoryId = :categoryId")int deactivateCategory(@Param("categoryId") Integer categoryId);
// src/main/java/com/shoplite/product/CatalogAdminService.java@Servicepublic class CatalogAdminService {
private final ProductRepository products;
CatalogAdminService(ProductRepository products) { this.products = products; }
@Transactional public int deactivateCategory(Integer categoryId) { return products.deactivateCategory(categoryId); }}
// src/main/java/com/shoplite/lab/ModifyingTour.java (profile "modifying")int rows = admin.deactivateCategory(2);System.out.println(rows + " products deactivated");--- deactivateCategory(2) through the @Transactional service DEBUG org.hibernate.SQL : update products p1_0 set is_active=false where p1_0.category_id=? 3 products deactivated
What this code does
- One UPDATE statement changed all three mobiles. No product was loaded into Java first.
- The
intreturn value is the number of rows MySQL reports for the statement;voidis also allowed when you do not need it. - The JPQL uses
Productandp.categoryId, and Hibernate wroteproductsandcategory_id, exactly as for SELECT queries.
Example 2 · An UPDATE without @Modifying
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// @Modifying removed by mistake@Query("update Product p set p.active = false where p.categoryId = :categoryId")int deactivateCategory(@Param("categoryId") Integer categoryId);--- deactivateCategory(2) through the @Transactional service ERROR o.s.boot.SpringApplication : Application run failed org.springframework.dao.InvalidDataAccessApiUsageException: Query executed via 'getResultList()' or 'getSingleResult()' must be a 'select' query [update Product p set p.active = false where p.categoryId = :categoryId] Caused by: java.lang.IllegalStateException: Query executed via 'getResultList()' or 'getSingleResult()' must be a 'select' query [update Product p set p.active = false where p.categoryId = :categoryId] ... 46 common frames omitted Caused by: org.hibernate.query.IllegalSelectQueryException: Expecting a SELECT Query [org.hibernate.query.sqm.tree.select.SqmSelectStatement], but found org.hibernate.query.sqm.tree.update.SqmUpdateStatement [update Product p set p.active = false where p.categoryId = :categoryId]
What this code does
- Without
@Modifying, Spring Data runs every@Queryas a SELECT (getResultList()). Hibernate sees an UPDATE and refuses: "must be a 'select' query". - The app started normally: the JPQL itself is valid. The mistake shows only when the method is called, so a test must call it.
The entity way would load every product, set active = false on each and let Hibernate send one UPDATE per product. update Product p set p.active = false where p.categoryId = :id does it in one statement, which matters when the category has thousands of products.
What can go wrong: forgetting @Modifying. The app starts, then the first call fails with "Query executed via 'getResultList()' or 'getSingleResult()' must be a 'select' query".
A transaction is required: TransactionRequiredException and @Transactional
@Transactional is an annotation that runs a method inside one database transaction, so its steps succeed or fail together. JPA allows UPDATE and DELETE queries only inside a transaction.
Call the update straight from the repository and it fails; call it through a service method and it works. See the error first.
Example 3 · Calling the update with no transaction
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// ModifyingTour: straight to the repository, no @Transactional anywhereSystem.out.println("--- deactivateCategory(2) called with no transaction");try { products.deactivateCategory(2);} catch (RuntimeException e) { System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());}--- deactivateCategory(2) called with no transaction InvalidDataAccessApiUsageException: No active transaction for update or delete query
What this code does
- Query methods you declare get no transaction by default (only the inherited CRUD methods do), and JPA allows UPDATE and DELETE queries only inside one.
- Hibernate 7 says "No active transaction for update or delete query"; underneath is JPA's
TransactionRequiredException. The fix is@Transactionalon the service method that calls it, as in Example 1.
The CRUD methods inherited from JpaRepository bring their own transactions, but the query methods you declare do not, so a @Modifying method called on its own fails with "No active transaction for update or delete query" (JPA's TransactionRequiredException, wrapped by Spring). The fix is to call it from a service method annotated with @Transactional. That is also the right design: the service method is the business operation ("deactivate this category"), and the transaction makes its steps all-or-nothing.
You can also put @Transactional on the repository method itself, but then each call is its own transaction and the service cannot combine it with other steps. Prefer the service. The Transactions module covers @Transactional in depth.
Fix the error
Add the missing transaction
The call fails. Pick the line that fixes the service method.
Which line fixes the service?
Error
InvalidDataAccessApiUsageException: No active transaction for update or delete query
Bulk queries bypass loaded objects: clearAutomatically and flushAutomatically
The persistence context is Hibernate's per-transaction cache of loaded entities. A bulk UPDATE goes straight to MySQL and never touches those objects, so a copy loaded earlier keeps its old values.
Read a price, run a bulk 10% rise, then read again. Does the second read see the new price? Try it without and with the clearing options.
Example 4 · Stale data after a bulk update, and the fix
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// ProductRepository@Modifying@Query("update Product p set p.price = p.price * :factor where p.categoryId = :categoryId")int raisePricesKeepingCache(@Param("categoryId") Integer categoryId, @Param("factor") BigDecimal factor);
@Modifying(flushAutomatically = true, clearAutomatically = true)@Query("update Product p set p.price = p.price * :factor where p.categoryId = :categoryId")int raisePrices(@Param("categoryId") Integer categoryId, @Param("factor") BigDecimal factor);
// ModifyingTour (part "stale"); TEN_PERCENT_MORE = new BigDecimal("1.10")System.out.println("--- without clearAutomatically");tx.executeWithoutResult(status -> { Product book = products.findById(9).orElseThrow(); System.out.println("before: " + book.getPrice()); products.raisePricesKeepingCache(5, TEN_PERCENT_MORE); System.out.println("after: " + products.findById(9).orElseThrow().getPrice() + " (stale)");});System.out.println("in the database now: " + products.findById(9).orElseThrow().getPrice());
System.out.println("--- with flushAutomatically and clearAutomatically");tx.executeWithoutResult(status -> { Product book = products.findById(10).orElseThrow(); System.out.println("before: " + book.getPrice()); book.setStock(21); // a change not yet sent to MySQL products.raisePrices(5, TEN_PERCENT_MORE); Product again = products.findById(10).orElseThrow(); System.out.println("after: " + again.getPrice() + ", stock " + again.getStock());});--- without clearAutomatically DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? before: 499.00 DEBUG org.hibernate.SQL : update products p1_0 set price=(p1_0.price*?) where p1_0.category_id=? after: 499.00 (stale) DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? in the database now: 548.90 --- with flushAutomatically and clearAutomatically DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? before: 715.00 DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? DEBUG org.hibernate.SQL : update products p1_0 set price=(p1_0.price*?) where p1_0.category_id=? DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? after: 786.50, stock 21
What this code does
- In the first block the UPDATE raised Clean Code to 548.90 in MySQL, but the second
findById(9)sent no SELECT: Hibernate returned the object it already held for this transaction, still at 499.00. - In the second block
flushAutomaticallyfirst sent the pending stock change (the row UPDATE), then the bulk UPDATE ran, thenclearAutomaticallyemptied Hibernate's cache, sofindById(10)read the fresh price 786.50 (715.00 × 1.10) and the saved stock 21. - The Pragmatic Programmer started at 715.00 because the first block had already raised every book by 10%.
findById returns the cached copy without even asking MySQL. clearAutomatically = true empties the persistence context after the query, so the next read loads fresh rows. But clearing also throws away changes you made to loaded entities and have not sent yet, so add flushAutomatically = true to send those pending changes before the query. Use the two together.
What can go wrong in an interview answer: thinking @Version checks or @PreUpdate and auditing callbacks run. A bulk UPDATE skips them all; it is plain SQL as far as entities are concerned.
Predict the output
Stale or fresh price?
Clean Code costs 499.00. A bulk query raises it by 10%. What does the last line print?
Round 1 of 2
The bulk query has plain @Modifying, no clearing.
Derived deleteBy vs a bulk delete query
A derived delete such as deleteByCategoryId(id) loads the matching entities and removes them one by one, so entity rules run. A bulk delete query is a single DELETE statement that skips those rules.
A fest-merch category has three products. Delete them once with the derived method and once with a bulk query, and count the statements.
Example 5 · Derived deleteBy vs a bulk DELETE query
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// ProductRepositorylong deleteByCategoryId(Integer categoryId);
@Modifying@Query("delete from Product p where p.categoryId = :categoryId")int deleteAllInCategory(@Param("categoryId") Integer categoryId);
// ModifyingTour (part "delete"): a "Fest Merch" category with 3 products, deleted twiceInteger fest = categories.save(new Category("Fest Merch", null)).getId();addFestProducts(fest);long removed = tx.execute(status -> products.deleteByCategoryId(fest));System.out.println(removed + " products deleted");
addFestProducts(fest);int deleted = tx.execute(status -> products.deleteAllInCategory(fest));System.out.println(deleted + " products deleted");DEBUG org.hibernate.SQL : insert into categories (name,parent_id) values (?,?) DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) --- derived deleteByCategoryId DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.category_id=? DEBUG org.hibernate.SQL : delete from products where product_id=? DEBUG org.hibernate.SQL : delete from products where product_id=? DEBUG org.hibernate.SQL : delete from products where product_id=? 3 products deleted DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?) --- bulk deleteAllInCategory DEBUG org.hibernate.SQL : delete p1_0 from products p1_0 where p1_0.category_id=? 3 products deleted
What this code does
- The derived
deleteByCategoryIdSELECTs the matching products, then removes each entity with its own DELETE: 1 + N statements. For 3 fest products that is fine; for 30,000 old log rows it is not. - The bulk query sends one DELETE for all of them. Both need a transaction; here
tx.executeprovides it. - The derived version is slower but runs entity rules: JPA cascades,
orphanRemovaland@PreRemovecallbacks. The bulk query skips all of them.
The derived delete needs a transaction and sends 1 SELECT and N DELETEs. That is slower, but it respects entity rules: cascades to child entities, orphanRemoval and @PreRemove callbacks all run. A bulk @Modifying @Query("delete from Product p where ...") skips every one of those rules; only the database's own foreign keys and ON DELETE CASCADE apply.
Choose the derived delete for a few rows with entity rules, and the bulk delete for many rows with no entity rules, such as clearing old audit rows.
Bulk update vs load-and-change: a 10% price rise for one category
A bulk query is one UPDATE or DELETE statement that changes many rows at once, without loading them into Java first.
A 10% rise for every book: load-and-change or one statement? Run both and count the SQL.
Example 6 · A 10% price rise for Books: load-and-change vs one bulk UPDATE
Runs in: the query-lab practice project (Spring Boot 4.1 + the ShopLite MySQL database)
// src/main/java/com/shoplite/product/CatalogAdminService.java (two more methods)/** One UPDATE statement for the whole category; MySQL rounds to DECIMAL(10,2). */@Transactionalpublic int raisePricesInBulk(Integer categoryId, BigDecimal factor) { return products.raisePrices(categoryId, factor);}
/** Loads every product and changes it in Java: one SELECT plus one UPDATE per product. */@Transactionalpublic int raisePricesOneByOne(Integer categoryId, BigDecimal factor) { List<Product> list = products.findByCategoryId(categoryId, Product.class); for (Product p : list) { p.setPrice(p.getPrice().multiply(factor).setScale(2, RoundingMode.HALF_UP)); } return list.size(); // no save() needed: changes to loaded entities are flushed at commit}--- 10% rise for Books, one by one DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.category_id=? DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? 3 products changed DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.category_id=? BK-CLEAN 548.90 BK-PRAG 715.00 BK-ATOMIC 438.90 --- 10% rise for Books, one bulk UPDATE DEBUG org.hibernate.SQL : update products p1_0 set price=(p1_0.price*?) where p1_0.category_id=? 3 rows updated DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.category_id=? BK-CLEAN 603.79 BK-PRAG 786.50 BK-ATOMIC 482.79
What this code does
- Load-and-change: 1 SELECT + 3 UPDATEs, each built from a Java object, with rounding done in Java by
setScale(2, HALF_UP). - Bulk: 1 UPDATE whatever the number of products; MySQL multiplies and rounds into the DECIMAL(10,2) column (548.90 × 1.10 = 603.79).
- The second rise was applied on top of the first, which is why the bulk results are about 21% above the original prices.
Load-and-change loads the entities, changes them in Java and lets Hibernate write each change at commit. It runs all entity logic (validation, @Version, auditing) and is easy to test, but sends one UPDATE per row. A bulk update such as set p.price = p.price * :factor sends one statement for any number of rows; MySQL does the arithmetic and rounds to the column's DECIMAL(10,2), so check that the rounding matches your business rule.
In ShopLite, a sale price change on one product goes through the entity. A 10% rise for every book before the new semester is a bulk update in an admin service, with clearAutomatically so nothing stale is read afterwards.
Order of execution
A safe bulk update, in order
Tap the steps in the order they happen.
Next step
Check your understanding
12 quick questions