Skip to lesson

save vs saveAndFlush, persist vs merge

Why does save() sometimes run an extra SELECT before an INSERT, and why do some saved changes get lost? Spring Data's save() quietly chooses between two different JPA calls.

SimpleJpaRepository.save: persist or merge

isNew is the question save() asks about an entity. Spring Data answers it without touching the database: the id is null (0 for a primitive id), or the wrapper @Version is null, or Persistable.isNew() says so.

save() asks one question: is this entity new? If yes it calls persist, if not it calls merge. The class below is the real code behind every repository.

Java
// org.springframework.data.jpa.repository.support.SimpleJpaRepository (Spring Data JPA 4.1)@Transactionalpublic <S extends T> S save(S entity) {    Assert.notNull(entity, ENTITY_MUST_NOT_BE_NULL);    if (entityInformation.isNew(entity)) {        entityManager.persist(entity);        return entity;    } else {        return entityManager.merge(entity);    }}

Example 1 · save() on a new object and on a detached object

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

SaveNewOrDetachedDemo.javaJava
// src/main/java/com/shoplite/lab/SaveNewOrDetachedDemo.javapackage com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Component;
import com.shoplite.category.Category;import com.shoplite.category.CategoryRepository;import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Component("save-new-or-detached")public class SaveNewOrDetachedDemo implements LabDemo {
    private final ProductRepository products;    private final CategoryRepository categories;
    public SaveNewOrDetachedDemo(ProductRepository products, CategoryRepository categories) {        this.products = products;        this.categories = categories;    }
    @Override    public void run() {        Category books = categories.findById(5).orElseThrow();
        System.out.println("-- 1. a new object: id is null");        Product guide = new Product("BK-GATE26", "GATE CSE Guide 2026", books, new BigDecimal("749.00"), 20);        Product saved = products.save(guide);        System.out.println("save() returned the same object? " + (saved == guide) + ", id=" + saved.getId());
        System.out.println("-- 2. a detached object: id is 6");        Product airdopes = products.findById(6).orElseThrow();   // detached once this call returns        airdopes.setPrice(new BigDecimal("1199.00"));        Product merged = products.save(airdopes);        System.out.println("save() returned the same object? " + (merged == airdopes));    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=save-new-or-detached"
DEBUG org.hibernate.SQL : select c1_0.category_id,c1_0.name,c1_0.parent_id from categories c1_0 where c1_0.category_id=?
-- 1. a new object: id is null
DEBUG org.hibernate.SQL : insert into products (is_active,category_id,name,price,sku,stock) values (?,?,?,?,?,?)
save() returned the same object? true, id=16
-- 2. a detached object: id is 6
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=?
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=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
save() returned the same object? false

What this code does

  • The new product has a null id, so save persists it: one INSERT, and the same object comes back with id 16.
  • The detached Airdopes object has id 6, so save merges it: Hibernate SELECTs the row into a fresh persistence context, copies the fields onto that managed copy and UPDATEs at commit. The returned object is not the one passed in.
  • The first SELECT of the second part is findById(6); the second one is merge loading the row.

Example 2 · An assigned id makes save() SELECT before every INSERT

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

Coupon.javaJava
// src/main/java/com/shoplite/coupon/Coupon.java (a lab-only table: coupons(code, percent_off))package com.shoplite.coupon;
import jakarta.persistence.Column;import jakarta.persistence.Entity;import jakarta.persistence.Id;import jakarta.persistence.Table;
/** A coupon whose id (the code) is chosen by a person, not generated by the database. */@Entity@Table(name = "coupons")public class Coupon {
    @Id    private String code;
    @Column(name = "percent_off", nullable = false)    private int percentOff;
    protected Coupon() {        // for JPA    }
    public Coupon(String code, int percentOff) {        this.code = code;        this.percentOff = percentOff;    }
    public String getCode() {        return code;    }
    public int getPercentOff() {        return percentOff;    }}
// src/main/java/com/shoplite/lab/AssignedIdDemo.javapackage com.shoplite.lab;
import org.springframework.stereotype.Component;
import com.shoplite.coupon.Coupon;import com.shoplite.coupon.CouponRepository;
@Component("assigned-id")public class AssignedIdDemo implements LabDemo {
    private final CouponRepository coupons;
    public AssignedIdDemo(CouponRepository coupons) {        this.coupons = coupons;    }
    @Override    public void run() {        System.out.println("-- saving a brand-new coupon FEST20");        coupons.save(new Coupon("FEST20", 20));        System.out.println("-- saving a brand-new coupon DIWALI10");        coupons.save(new Coupon("DIWALI10", 10));    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=assigned-id"
-- saving a brand-new coupon FEST20
DEBUG org.hibernate.SQL : select c1_0.code,c1_0.percent_off from coupons c1_0 where c1_0.code=?
DEBUG org.hibernate.SQL : insert into coupons (percent_off,code) values (?,?)
-- saving a brand-new coupon DIWALI10
DEBUG org.hibernate.SQL : select c1_0.code,c1_0.percent_off from coupons c1_0 where c1_0.code=?
DEBUG org.hibernate.SQL : insert into coupons (percent_off,code) values (?,?)

What this code does

  • The coupon code is the id and is set by the constructor, so it is never null and Spring Data treats every coupon as not new. save calls merge.
  • merge must find out whether the row exists, so each brand-new coupon costs a SELECT and then the INSERT: twice the round trips.
  • The fix is to let the entity say whether it is new by implementing Persistable (Practice 3), or to add a wrapper @Version field, which is null on new objects.

"New" is decided from the object alone. With no @Version field (or a primitive one), an entity is new when its id is null (0 for a primitive number id); with a wrapper-type @Version field, when the version is null. An entity that implements Persistable decides itself through isNew().

ShopLite's generated Integer ids work well: a new object has a null id. It goes wrong when you choose the id, like a coupon code: the id is never null, so save() always merges, and merge first runs a SELECT to look for the row (Example 2).

merge returns a different, managed copy

merge(detached) finds or loads the managed entity with the same id, copies every field of the detached object onto it and returns that managed object. The object you passed in stays detached.

The listing merges a detached product, then changes both the old object and the returned copy. Only one of those changes reaches the database.

Example 3 · Keep the object merge returns

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

MergeCopyDemo.javaJava
// src/main/java/com/shoplite/lab/MergeCopyDemo.javapackage com.shoplite.lab;
import org.springframework.stereotype.Component;import org.springframework.transaction.support.TransactionTemplate;
import com.shoplite.product.Product;
import jakarta.persistence.EntityManager;
@Component("merge-copy")public class MergeCopyDemo implements LabDemo {
    private final EntityManager em;    private final TransactionTemplate tx;
    public MergeCopyDemo(EntityManager em, TransactionTemplate tx) {        this.em = em;        this.tx = tx;    }
    @Override    public void run() {        Product detached = tx.execute(status -> em.find(Product.class, 12));   // Cotton Kurta, stock 35
        tx.executeWithoutResult(status -> {            Product managed = em.merge(detached);            System.out.println("merge returned a different object? " + (managed != detached));            System.out.println("detached managed=" + em.contains(detached) + ", returned managed=" + em.contains(managed));
            detached.setStock(0);       // change on the OLD object: lost            managed.setStock(34);            System.out.println("-- transaction commits");        });
        Product fromDb = tx.execute(status -> em.find(Product.class, 12));        System.out.println("stock in the database: " + fromDb.getStock());    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=merge-copy"
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=?
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=?
merge returned a different object? true
detached managed=false, returned managed=true
-- transaction commits
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_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=?
stock in the database: 34

What this code does

  • em.merge(detached) loads product 12 and returns a different object, which is managed; the one passed in stays detached.
  • Setting stock 0 on the detached object does nothing. Setting 34 on the returned copy is saved: the database ends with 34.

Always continue with the returned object: Product managed = products.save(detached);. Changes made afterwards to the old reference are silently lost, because nothing tracks it. That is why save() returns a value at all.

Merge copies all fields, including ones you did not mean to change. If the detached copy is old, its old values overwrite newer data in the row; the last section turns this into a rule.

Fix the error

Keep what merge returns

Read the failure, then pick the line that fixes it.

Round 1 of 2

A sale lowers the stock, but the row keeps the old value.

@Transactional
public void sell(Product detached) {
products.save(detached);
detached.setStock(detached.getStock() - 1);
}

Error

Test failed: expected stock 34 but was 35
No UPDATE appears in the SQL log

saveAndFlush: constraint errors right away

saveAndFlush(entity) is save(entity) followed by flush(). The pending SQL runs at that line, so a broken UNIQUE constraint surfaces as a DataIntegrityViolationException right there, inside your service.

A duplicate e-mail is saved with saveAndFlush, and the service turns the error into a 409 inside the method.

Example 4 · saveAndFlush turns a duplicate e-mail into a 409 inside the service

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

CustomerEmailService.javaJava
// src/main/java/com/shoplite/lab/CustomerEmailService.javapackage com.shoplite.lab;
import org.springframework.dao.DataIntegrityViolationException;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;
@Servicepublic class CustomerEmailService {
    private final CustomerRepository customers;
    public CustomerEmailService(CustomerRepository customers) {        this.customers = customers;    }
    @Transactional    public Customer changeEmail(int customerId, String newEmail) {        Customer customer = customers.findById(customerId).orElseThrow();        customer.setEmail(newEmail);        try {            customers.saveAndFlush(customer);           // the UPDATE runs here, not at commit        } catch (DataIntegrityViolationException e) {            throw new EmailTakenException(newEmail);        }        System.out.println("   e-mail changed, the rest of the method runs");        return customer;    }
    public static class EmailTakenException extends RuntimeException {        public EmailTakenException(String email) {            super("A customer with e-mail " + email + " already exists.");        }    }}
// src/main/java/com/shoplite/lab/SaveAndFlushDemo.java (its run method)@Overridepublic void run() {    System.out.println("-- Ravi takes a free e-mail");    System.out.println("   " + service.changeEmail(2, "ravi.k@example.com"));
    System.out.println("-- Ravi tries Asha's e-mail");    try {        service.changeEmail(2, "asha.rao@example.com");    } catch (CustomerEmailService.EmailTakenException e) {        System.out.println("   409 Conflict: " + e.getMessage());    }}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=save-and-flush"
-- Ravi takes a free e-mail
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=?
DEBUG org.hibernate.SQL : update customers set email=?,full_name=?,phone=? where customer_id=?
   e-mail changed, the rest of the method runs
   Customer[id=2, email=ravi.k@example.com]
-- Ravi tries Asha's e-mail
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=?
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'
   409 Conflict: A customer with e-mail asha.rao@example.com already exists.

What this code does

  • For a free e-mail the UPDATE runs at saveAndFlush, before "the rest of the method runs". The method continues normally.
  • For Asha's e-mail the UPDATE fails at that same line. The service catches DataIntegrityViolationException and throws its own EmailTakenException. In ShopLite the same spot throws AlreadyExistsException, which the global handler turns into 409 already-exists (the module project).
  • The transaction is still rolled back, which is what we want: nothing of the failed change is saved.

Use it only where you need the error early: a unique e-mail or SKU check that must also survive two requests at the same moment. Everywhere else, normal write-behind is fine and cheaper.

Once the flush fails, the transaction is marked rollback-only. Catch the exception only to throw a meaningful one: if you catch it and return normally, the commit fails with UnexpectedRollbackException (Practice 6).

Hibernate 7 removed save, update and saveOrUpdate

Session.save, update and saveOrUpdate were Hibernate's own methods for saving objects. They were deprecated in Hibernate 6 and removed in Hibernate 7, the version Spring Boot 4.1 uses.

Code copied from older tutorials may call session.save(...). The listing shows what that looks like on Hibernate 7.

Example 5 · Old Session.save code no longer compiles on Hibernate 7

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

OldSessionApi.javaJava
// src/main/java/com/shoplite/lab/OldSessionApi.java (copied from a Hibernate 5 tutorial)package com.shoplite.lab;
import org.hibernate.Session;
import com.shoplite.product.Product;
import jakarta.persistence.EntityManager;
public class OldSessionApi {
    void copyFromOldTutorial(EntityManager em, Product product) {        Session session = em.unwrap(Session.class);        session.save(product);        session.saveOrUpdate(product);    }}
// Hibernate 7 / JPA replacementsem.persist(product);                    // a new objectProduct managed = em.merge(detached);
Sample output
$ mvn compile
    ...
[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] /C:/projects/persistence-lab/src/main/java/com/shoplite/lab/OldSessionApi.java:[13,16] cannot find symbol
  symbol:   method save(com.shoplite.product.Product)
  location: variable session of type org.hibernate.Session
[ERROR] /C:/projects/persistence-lab/src/main/java/com/shoplite/lab/OldSessionApi.java:[14,16] cannot find symbol
  symbol:   method saveOrUpdate(com.shoplite.product.Product)
  location: variable session of type org.hibernate.Session
[INFO] 2 errors 
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE

What this code does

  • Hibernate 7's Session has no save or saveOrUpdate (nor update), so the compiler reports "cannot find symbol" for each call.
  • Replace them with persist and merge, or better, with Spring Data repositories and load-and-change updates.

The replacements are the JPA methods: persist for a new object, merge for a detached one (keep the returned copy). For "update this row", the best answer is usually neither: load the entity in the transaction and change it. In Spring Data code you rarely touch Session at all; save, saveAndFlush and dirty checking cover the cases.

StatelessSession (a Hibernate API for bulk work without a persistence context) still has insert and update. That is a different, rarely needed tool.

The update-from-DTO pattern: load, change, commit

A lost update happens when a stale copy of an entity is saved over newer data. Merge writes the old values of every field, so a change made meanwhile in the database, like stock reduced by an order, disappears.

The listing applies one stock change twice: from a stale detached copy, and with load, change, commit. Compare the stock left in the database.

Example 6 · A stale copy loses a sale; load-change-commit does not

Runs in: the persistence-lab practice project (Spring Boot 4.1, ShopLite database)

ProductAdminService.javaJava
// src/main/java/com/shoplite/lab/ProductAdminService.javapackage com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class ProductAdminService {
    private final ProductRepository products;
    public ProductAdminService(ProductRepository products) {        this.products = products;    }
    // Wrong: saves a whole object that was loaded earlier, maybe minutes ago    @Transactional    public Product saveEdited(Product editedCopy) {        return products.save(editedCopy);    }
    @Transactional    public Product changePrice(int id, BigDecimal newPrice) {        Product product = products.findById(id).orElseThrow();        product.setPrice(newPrice);        return product;    }
    @Transactional    public void sellOne(int id) {        Product product = products.findById(id).orElseThrow();        product.setStock(product.getStock() - 1);    }}
// src/main/java/com/shoplite/lab/MergeLostUpdateDemo.java (its run method)@Overridepublic void run() {    System.out.println("-- wrong: save a stale copy");    Product formCopy = products.findById(13).orElseThrow();    admin.sellOne(13);    formCopy.setPrice(new BigDecimal("2299.00"));    admin.saveEdited(formCopy);    System.out.println("stock now: " + products.findById(13).orElseThrow().getStock());
    System.out.println("-- right: load, change, commit");    admin.sellOne(14);    admin.changePrice(14, new BigDecimal("1799.00"));    System.out.println("stock now: " + products.findById(14).orElseThrow().getStock());}
Sample output
$ mvn spring-boot:run -Dspring-boot.run.arguments="--demo=merge-lost-update"
-- wrong: save a stale copy
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=?
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=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_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=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_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=?
stock now: 18
-- right: load, change, commit
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=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_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=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_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=?
stock now: 14

What this code does

  • The admin's copy of the Running Shoes was loaded with stock 18. A customer then bought a pair (stock 17). saveEdited merged the old copy, which wrote all its fields back: the stock is 18 again and the sale has vanished from the stock count.
  • changePrice loads product 14 inside its own transaction, after the sale, and changes only the price. The UPDATE carries the current stock, so the cooker correctly ends at 14.
  • Load-change-commit still has a small race window if two transactions run at exactly the same time. The Transactions module closes it with optimistic locking (@Version).

The safe way to apply a request to a row is load, change, commit: in one @Transactional method, load the managed entity by id, copy only the fields the request sends and return. Dirty checking writes the UPDATE with the current values of every other field.

ShopLite applies this everywhere: controllers receive request DTOs, services load entities and change them, and entities never come from the client and never go back to it.

Next step

Check your understanding

12 quick questions