Flush: when SQL is actually sent
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Your service calls save() and prints a line, yet the SQL shows up later, after the method has "finished". A failing INSERT may not fail where you expect either. When does the SQL really run?
Write-behind: changes wait for the flush
Write-behind means Hibernate collects changes in the persistence context and writes them later, at a flush, instead of after every setter or save() call.
The listing changes the stock of three products and prints a line after each change. Watch where the UPDATE lines appear in the log.
Example 1 · Three stock changes, three UPDATEs at the end
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/WriteBehindDemo.javapackage com.shoplite.lab;
import java.util.List;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("write-behind")public class WriteBehindDemo implements LabDemo {
private final ProductRepository products;
public WriteBehindDemo(ProductRepository products) { this.products = products; }
@Override @Transactional public void run() { for (int id : List.of(1, 2, 3)) { // three phones sold at the college fest stall Product phone = products.findById(id).orElseThrow(); phone.setStock(phone.getStock() - 1); System.out.println("stock of " + phone.getSku() + " is now " + phone.getStock() + " (in memory)"); } System.out.println("-- method ends, Spring commits"); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=write-behind" 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=? stock of MOB-RN13 is now 39 (in memory) 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=? stock of MOB-GM35 is now 24 (in memory) 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=? stock of MOB-IP15 is now 7 (in memory) -- method ends, Spring commits 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=?
What this code does
- Each SELECT runs at
findById, when Hibernate needs the data. Each stock change only touches the Java object, so the three "in memory" lines print with no SQL between them. - All three UPDATEs come after "method ends": Spring flushes at commit, and only then does Hibernate send the changes it collected.
A flush sends SQL inside the open transaction; it does not commit. Flushed changes can still be rolled back, and other transactions cannot see them until the commit. One flush can send all changes together, in a fixed order (inserts, then updates, then deletes), and can group similar statements into one JDBC batch. A transaction that changes the same product five times sends one UPDATE, not five.
The price is surprise: in the log your print lines come first and the SQL at the end, and in a debugger stepping over save() shows no SQL at all.
Order of execution
When does the UPDATE run?
Tap the steps in the order they happen.
Flush triggers: commit, queries and flush()
A flush is the moment Hibernate sends the pending INSERT, UPDATE and DELETE statements of the persistence context to the database. It happens inside the open transaction and is not a commit.
Hibernate flushes at commit, before a query that reads a changed table, and when you call flush(). The listing shows each trigger in the log.
Example 2 · What makes Hibernate flush early
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/FlushTriggersDemo.javapackage com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.customer.CustomerRepository;import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
import jakarta.persistence.EntityManager;
@Component("flush-triggers")public class FlushTriggersDemo implements LabDemo {
private final ProductRepository products; private final CustomerRepository customers; private final EntityManager em;
public FlushTriggersDemo(ProductRepository products, CustomerRepository customers, EntityManager em) { this.products = products; this.customers = customers; this.em = em; }
@Override @Transactional public void run() { Product laptop = products.findById(4).orElseThrow(); laptop.setPrice(new BigDecimal("39990.00")); System.out.println("1. price changed in memory");
System.out.println("2. query on customers: " + customers.count()); System.out.println("3. query on products: " + products.countByPriceLessThan(new BigDecimal("40000")));
laptop.setStock(10); System.out.println("4. stock changed in memory, calling flush()"); products.flush();
System.out.println("5. flush() returned; native SQL next"); laptop.setStock(9); Object n = em.createNativeQuery("select count(*) from customers").getSingleResult(); System.out.println("6. native query: " + n); System.out.println("-- method ends, Spring commits"); }}
// added to ProductRepositorylong countByPriceLessThan(BigDecimal price);$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=flush-triggers" 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=? 1. price changed in memory DEBUG org.hibernate.SQL : select count(*) from customers c1_0 2. query on customers: 8 DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? DEBUG org.hibernate.SQL : select count(p1_0.product_id) from products p1_0 where p1_0.price<? 3. query on products: 13 4. stock changed in memory, calling flush() DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? 5. flush() returned; native SQL next DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=? DEBUG org.hibernate.SQL : select count(*) from customers 6. native query: 8 -- method ends, Spring commits
What this code does
- Step 2 counts customers: no product table involved, so no flush. Step 3 counts products, so Hibernate first sends the pending laptop UPDATE; the count is 13, which includes the laptop at its new price of 39990.00 (12 before the change).
- Step 4 calls
flush()and the stock UPDATE runs right there. In step 6 the native query is oncustomersonly, yet Hibernate flushes the product change first: it cannot read raw SQL to see which tables it uses. - At commit nothing is left to send, so no SQL follows "method ends".
The three triggers: at commit, Spring flushes and then commits; before a query on a table with pending changes, which is FlushModeType.AUTO, the default, so your own query sees your own changes; and when you call flush() on the repository or the EntityManager.
AUTO is smart about JPQL: before a query on Customer it does not flush pending product changes, because the query cannot see them. A native SQL query is different: Hibernate cannot tell which tables raw SQL touches, so it flushes everything first. FlushModeType.COMMIT turns the query trigger off, so queries may not see your own unsaved changes; it is rarely what you want, and the Practice tab shows the stale count it gives.
Constraint errors appear at flush, not at save()
DataIntegrityViolationException is the Spring exception that wraps a database constraint error, such as a duplicate UNIQUE value. With write-behind it is thrown at the flush, often at commit, not at save().
Saving a customer with an e-mail that already exists looks fine at save() and fails only at commit. The listing shows where the exception comes from.
Example 3 · A duplicate e-mail fails at commit, not at save()
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/EmailChangeService.javapackage com.shoplite.lab;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;
@Servicepublic class EmailChangeService {
private final CustomerRepository customers;
public EmailChangeService(CustomerRepository customers) { this.customers = customers; }
@Transactional public void changeEmail(int customerId, String newEmail) { Customer customer = customers.findById(customerId).orElseThrow(); customer.setEmail(newEmail); customers.save(customer); System.out.println(" save() returned without an error"); System.out.println(" ...more work in the same method..."); }
@Transactional public void changeEmailAndFlush(int customerId, String newEmail) { Customer customer = customers.findById(customerId).orElseThrow(); customer.setEmail(newEmail); System.out.println(" calling flush()"); customers.flush(); System.out.println(" this line never runs"); }}
// src/main/java/com/shoplite/lab/DuplicateEmailDemo.java (its run method)@Overridepublic void run() { System.out.println("-- Ravi (customer 2) takes Asha's e-mail, error at commit"); try { service.changeEmail(2, "asha.rao@example.com"); System.out.println(" changeEmail finished"); } catch (DataIntegrityViolationException e) { System.out.println(" caught in the caller: " + e.getClass().getSimpleName()); System.out.println(" cause: " + e.getMostSpecificCause().getMessage()); }
System.out.println("-- the same change with flush(), error inside the method"); try { service.changeEmailAndFlush(2, "asha.rao@example.com"); } catch (DataIntegrityViolationException e) { System.out.println(" caught in the caller: " + e.getClass().getSimpleName()); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=duplicate-email" -- Ravi (customer 2) takes Asha's e-mail, error at commit DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? save() returned without an error ...more work in the same method... DEBUG org.hibernate.SQL : update customers set email=?,full_name=?,phone=? where customer_id=? WARN org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1062, SQLState: 23000 WARN org.hibernate.orm.jdbc.error : Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' caught in the caller: DataIntegrityViolationException cause: Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' -- the same change with flush(), error inside the method DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where c1_0.customer_id=? calling flush() DEBUG org.hibernate.SQL : update customers set email=?,full_name=?,phone=? where customer_id=? WARN org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1062, SQLState: 23000 WARN org.hibernate.orm.jdbc.error : Duplicate entry 'asha.rao@example.com' for key 'customers.uq_customers_email' caught in the caller: DataIntegrityViolationException
What this code does
save()returned with no error and the method ran to its end. The UPDATE was sent only at commit, MySQL rejected it (error 1062, theuq_customers_emailkey), and the caller receivedDataIntegrityViolationException.- With
flush()the same UPDATE runs inside the method, so the exception is thrown at theflush()line and "this line never runs". Now the service could catch it and answer 409, which the next lesson does withsaveAndFlush. - The two WARN lines come from Hibernate's JDBC error logger. They show the real MySQL message; never send that text to API clients.
MySQL checks UNIQUE, foreign key and CHECK constraints when it runs the statement, and with write-behind the statement runs at the flush. At commit the exception leaves the service method after its last line has run, so the service cannot turn it into a clear 409; in ShopLite it reaches the global handler as a generic 500. Work done after save(), like sending a confirmation SMS, has already happened for a change that then failed.
The fix is to flush on purpose where the error must be caught: call flush() (or saveAndFlush, next lesson) inside the method, catch DataIntegrityViolationException there and throw your own exception. Checking first with existsByEmail... gives a friendly message, but only the database constraint is safe when two requests arrive at the same moment.
Fix the error
Fail inside the method
Read the real error, then pick the line that makes it fail inside the method.
Round 1 of 2
The SMS is sent, and then the duplicate e-mail fails at commit.
Error
DataIntegrityViolationException: could not execute statement [Duplicate entry 'asha@example.com' for key 'customers.uk_customers_email'] thrown at commit, after sms.sendWelcome(c)
IDENTITY ids: INSERT at persist, no insert batching
JDBC batching sends many similar statements to the database in one round trip instead of one by one. It is turned on with spring.jpa.properties.hibernate.jdbc.batch_size.
ShopLite's tables use AUTO_INCREMENT ids. The first listing shows the INSERT running inside save(); the second shows batching working for UPDATEs but not for those INSERTs.
Example 4 · IDENTITY: the INSERT runs inside save()
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/IdentityInsertDemo.javapackage com.shoplite.lab;
import java.util.List;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.category.Category;import com.shoplite.category.CategoryRepository;
@Component("identity-insert")public class IdentityInsertDemo implements LabDemo {
private final CategoryRepository categories;
public IdentityInsertDemo(CategoryRepository categories) { this.categories = categories; }
@Override @Transactional public void run() { Category books = categories.getReferenceById(5); for (String name : List.of("Exam Guides", "Novels", "Comics")) { System.out.println("persisting " + name); Category saved = categories.save(new Category(name, books)); System.out.println(" id right after save(): " + saved.getId()); } System.out.println("-- method ends, Spring commits"); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=identity-insert" persisting Exam Guides DEBUG org.hibernate.SQL : insert into categories (name,parent_id) values (?,?) id right after save(): 8 persisting Novels DEBUG org.hibernate.SQL : insert into categories (name,parent_id) values (?,?) id right after save(): 9 persisting Comics DEBUG org.hibernate.SQL : insert into categories (name,parent_id) values (?,?) id right after save(): 10 -- method ends, Spring commits
What this code does
- Each INSERT appears between "persisting ..." and "id right after save()": it is not delayed to the commit like the UPDATEs in Example 1.
- Hibernate needs MySQL to run the INSERT to learn the AUTO_INCREMENT id (8, 9, 10), because the new object must be stored in the persistence context under its id.
Example 5 · Batching works for UPDATEs, not for IDENTITY INSERTs
Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)
// src/main/java/com/shoplite/lab/BatchingDemo.javapackage com.shoplite.lab;
import java.util.List;
import org.springframework.stereotype.Component;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.category.Category;import com.shoplite.category.CategoryRepository;import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("batching")public class BatchingDemo implements LabDemo {
private final CategoryRepository categories; private final ProductRepository products;
public BatchingDemo(CategoryRepository categories, ProductRepository products) { this.categories = categories; this.products = products; }
@Override @Transactional public void run() { Category books = categories.getReferenceById(5); for (String name : List.of("Exam Guides", "Novels", "Comics")) { categories.save(new Category(name, books)); // IDENTITY: one INSERT each, right now } for (Product book : products.findAllById(List.of(9, 10, 11))) { book.setStock(book.getStock() + 10); // UPDATEs wait for the flush } System.out.println("-- method ends, Spring commits"); }}$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=batching --spring.jpa.properties.hibernate.jdbc.batch_size=20 --spring.jpa.properties.hibernate.generate_statistics=true --logging.level.org.hibernate.session.metrics=DEBUG" DEBUG org.hibernate.SQL : insert into categories (name,parent_id) values (?,?) DEBUG org.hibernate.SQL : insert into categories (name,parent_id) values (?,?) DEBUG org.hibernate.SQL : insert into categories (name,parent_id) values (?,?) 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 (?,?,?) -- method ends, Spring commits 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=? DEBUG org.hibernate.session.metrics : HHH000401: Logging session metrics: 9191800 ns preparing 5 JDBC statements 25585500 ns executing 4 JDBC statements 10734800 ns executing 1 JDBC batches ... (other metrics trimmed)
What this code does
hibernate.jdbc.batch_size=20turns batching on andgenerate_statisticsprints the session metrics at the end. The SQL log still shows every statement, batched or not.- The metrics say 4 statements ran on their own (the 3 INSERTs and the SELECT) and 1 batch was sent: the 3 UPDATEs went to MySQL together in one round trip.
- The INSERTs could not join a batch: with IDENTITY each one must run alone to return its new id.
With GenerationType.IDENTITY the database chooses the id while running the INSERT, but a managed entity must have its id at once, because the persistence context is a map keyed by id. So persist (and save of a new entity) sends the INSERT immediately, the one exception to write-behind. An INSERT that breaks a constraint therefore fails at save() itself; Practice 2 shows it with a duplicate category name.
Each IDENTITY INSERT must run alone to return its id, so batching cannot group them; UPDATEs and DELETEs still batch. For an order with a handful of rows that is fine. Bulk imports of thousands of rows should use JDBC batch inserts or a database with sequences (PostgreSQL, Oracle), where Hibernate fetches ids in blocks.
Next step
Check your understanding
12 quick questions