Soft delete in Spring Data JPA

A soft delete marks a row as deleted instead of removing it, so that it can be restored, audited or kept for reporting. Hibernate offers two ways to make this transparent to repositories, and both have limits that are easy to miss. This page runs each approach and each trap, from bulk deletes that really delete to references that silently turn null.

Contents

What a soft delete changes

A hard delete runs DELETE FROM customer WHERE id = ?, and the row is gone. A soft delete runs an UPDATE that sets a flag or a timestamp, and every query from then on has to skip the flagged rows. Teams choose it for several reasons: to undo mistakes, to keep history that other tables still refer to, or because regulations say records must be kept.

The hard part is not the UPDATE; it is making every read skip deleted rows, including the ones you forget about. Writing and deleted = false in every query does not scale. Hibernate can add the condition for you, in two ways:

Soft delete approaches with Hibernate
ApproachSinceHow it worksBest for
@SQLDelete + @SQLRestriction@SQLRestriction in Hibernate 6.3 (replacing @Where)You write the UPDATE that replaces the delete, and an SQL condition added to every queryCustom columns, extra fields such as deleted_by
@SoftDeleteHibernate 6.4; TIMESTAMP strategy in 7.0Hibernate manages a column and writes both the update and the conditionNew code: less to write, and bulk deletes are handled too
@FilterHibernate 3A condition switched on per session, with parametersAdmin views that show deleted rows on demand
Explicit status columnAnyQueries filter by status themselvesRows that are archived rather than deleted, and still shown somewhere

All of these work below Spring Data: the repository still calls EntityManager.remove, and Hibernate turns it into an update. The examples run Spring Boot 4.1 with Spring Data JPA 4.1 and Hibernate 7.4 on H2, and print the SQL Hibernate sends where it matters.

@SQLDelete with @SQLRestriction

This is the classic setup: a boolean deleted field, an @SQLDelete statement that sets it, and an @SQLRestriction that hides flagged rows. Three customers are saved, and Bob is deleted and then restored:

Java
package soft.sqldelete;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.List;
import java.util.Map;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.SQLRestriction;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

@SpringBootApplication
public class SqlDeleteBasics {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(SqlDeleteBasics.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            CustomerRepository customers = context.getBean(CustomerRepository.class);
            List<Customer> saved = customers.saveAll(List.of(
                    new Customer("Ann"), new Customer("Bob"), new Customer("Cara")));
            Long bobId = saved.get(1).getId();
            LoggingSystem.get(SqlDeleteBasics.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);

            System.out.println("-- deleteById(Bob)");
            customers.deleteById(bobId);
            System.out.println("-- what the repository sees");
            System.out.println("findAll()     = " + customers.findAll());
            System.out.println("findById(Bob) = " + customers.findById(bobId));
            System.out.println("count()       = " + customers.count());
            System.out.println("-- what is really in the table (native query)");
            System.out.println(customers.allRows());
            System.out.println("-- restore Bob");
            customers.restore(bobId);
            System.out.println("findAll()     = " + customers.findAll());
        }
    }
}

@Entity
@SQLDelete(sql = "UPDATE customer SET deleted = TRUE WHERE id = ?")
@SQLRestriction("deleted = FALSE")
class Customer {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private boolean deleted;

    protected Customer() {
    }

    Customer(String name) {
        this.name = name;
    }

    Long getId() {
        return id;
    }

    @Override
    public String toString() {
        return name;
    }
}

interface CustomerRepository extends JpaRepository<Customer, Long> {
    @Query(value = "SELECT name || CASE WHEN deleted THEN ' (deleted)' ELSE '' END"
            + " FROM customer ORDER BY id", nativeQuery = true)
    List<String> allRows();

    @Modifying
    @Transactional
    @Query(value = "UPDATE customer SET deleted = FALSE WHERE id = ?1", nativeQuery = true)
    int restore(Long id);
}
Output
-- deleteById(Bob)
SQL: select c1_0.id,c1_0.deleted,c1_0.name from customer c1_0 where c1_0.id=? and (c1_0.deleted = false)
SQL: UPDATE customer SET deleted = TRUE WHERE id = ?
-- what the repository sees
SQL: select c1_0.id,c1_0.deleted,c1_0.name from customer c1_0 where (c1_0.deleted = false)
findAll()     = [Ann, Cara]
SQL: select c1_0.id,c1_0.deleted,c1_0.name from customer c1_0 where c1_0.id=? and (c1_0.deleted = false)
findById(Bob) = Optional.empty
SQL: select count(*) from customer c1_0 where (c1_0.deleted = false)
count()       = 2
-- what is really in the table (native query)
SQL: SELECT name || CASE WHEN deleted THEN ' (deleted)' ELSE '' END FROM customer ORDER BY id
[Ann, Bob (deleted), Cara]
-- restore Bob
SQL: UPDATE customer SET deleted = FALSE WHERE id = ?
SQL: select c1_0.id,c1_0.deleted,c1_0.name from customer c1_0 where (c1_0.deleted = false)
findAll()     = [Ann, Bob, Cara]
SQL: drop table if exists customer cascade 
SQL: drop sequence if exists customer_seq
  • deleteById loaded Bob, then ran the custom UPDATE customer SET deleted = TRUE instead of a DELETE. The statement text is exactly what the annotation says.
  • Every following query, including findById and count, had (deleted = false) added to its where clause. Bob is gone from findAll, findById returns empty, and the count is 2.
  • The native query saw all three rows, with Bob flagged. Native SQL is passed to the database unchanged, so @SQLRestriction does not apply to it.
  • Restoring needs a native UPDATE for the same reason in reverse: JPQL and repository methods cannot even find Bob any more. After it, Bob is back in findAll.

The restriction is plain SQL, pasted into every query of the entity, so it must use column names, not field names. @SQLRestriction replaced @Where, which is deprecated in Hibernate 6.3 and later. In Spring Boot 3 code you will still see @Where(clause = "deleted = false"); it does the same thing.

Hibernate's @SoftDelete

@SoftDelete needs no SQL and no field in the class: Hibernate adds the column, writes the update, and adds the condition itself. Notes use the default strategy, a boolean deleted column. Tickets use the TIMESTAMP strategy, which records when the row was deleted:

Java
package soft.annotation;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.List;
import java.util.Map;
import org.hibernate.annotations.SoftDelete;
import org.hibernate.annotations.SoftDeleteType;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

@SpringBootApplication
public class SoftDeleteAnnotation {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(SoftDeleteAnnotation.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "logging.pattern.console", "%logger{0}: %msg%n"));
        try (var context = app.run(args)) {
            NoteRepository notes = context.getBean(NoteRepository.class);
            TicketRepository tickets = context.getBean(TicketRepository.class);
            Note note = notes.save(new Note("call the bank"));
            notes.save(new Note("buy milk"));
            Ticket ticket = tickets.save(new Ticket("printer jam"));
            LoggingSystem.get(SoftDeleteAnnotation.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.DEBUG);

            System.out.println("-- delete a note (strategy DELETED, the default)");
            notes.delete(note);
            System.out.println("notes: " + notes.findAll());
            System.out.println("-- delete a ticket (strategy TIMESTAMP)");
            tickets.delete(ticket);
            System.out.println("tickets: " + tickets.findAll());
            LoggingSystem.get(SoftDeleteAnnotation.class.getClassLoader())
                    .setLogLevel("org.hibernate.SQL", LogLevel.WARN);
            System.out.println("-- the tables");
            System.out.println("note  : " + notes.rawRows());
            System.out.println("ticket: deleted column set = " + tickets.deletedIsSet());
        }
    }
}

@Entity
@SoftDelete
class Note {
    @Id
    @GeneratedValue
    private Long id;
    private String text;

    protected Note() {
    }

    Note(String text) {
        this.text = text;
    }

    @Override
    public String toString() {
        return text;
    }
}

@Entity
@SoftDelete(strategy = SoftDeleteType.TIMESTAMP)
class Ticket {
    @Id
    @GeneratedValue
    private Long id;
    private String title;

    protected Ticket() {
    }

    Ticket(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return title;
    }
}

interface NoteRepository extends JpaRepository<Note, Long> {
    @Query(value = "SELECT text || ' deleted=' || deleted FROM note ORDER BY id",
            nativeQuery = true)
    List<String> rawRows();
}

interface TicketRepository extends JpaRepository<Ticket, Long> {
    @Query(value = "SELECT deleted IS NOT NULL FROM ticket", nativeQuery = true)
    boolean deletedIsSet();
}
Output
-- delete a note (strategy DELETED, the default)
SQL: select n1_0.id,n1_0.text from note n1_0 where n1_0.deleted=false and n1_0.id=?
SQL: update note set deleted=true where id=? and deleted=false
SQL: select n1_0.id,n1_0.text from note n1_0 where n1_0.deleted=false
notes: [buy milk]
-- delete a ticket (strategy TIMESTAMP)
SQL: select t1_0.id,t1_0.title from ticket t1_0 where t1_0.deleted is null and t1_0.id=?
SQL: update ticket set deleted=localtimestamp where id=? and deleted is null
SQL: select t1_0.id,t1_0.title from ticket t1_0 where t1_0.deleted is null
tickets: []
-- the tables
note  : [call the bank deleted=TRUE, buy milk deleted=FALSE]
ticket: deleted column set = true
  • Deleting a note ran update note set deleted=true where id=? and deleted=false. The extra and deleted=false means a second delete of the same row changes nothing.
  • Queries got where n1_0.deleted=false, so only "buy milk" is listed. The Note class has no deleted field at all; the column exists only in the table, as the native query shows.
  • With TIMESTAMP, the column holds null for live rows and the deletion time for deleted ones. The delete set it to localtimestamp, and queries filtered on deleted is null.

Other strategies and options: SoftDeleteType.ACTIVE stores the opposite flag (an active column that is true for live rows), columnName renames the column, and converter stores the flag as, for example, 'Y' and 'N'. Because the column is not mapped to a field, Java code cannot read whether an entity is deleted; that is deliberate, since deleted entities are never loaded.

Traps: real deletes, unique keys and vanishing references

Each case below does something ordinary, and each gives a result that surprises people who rely on soft delete:

Java
package soft.traps;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import java.util.List;
import java.util.Map;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.SQLRestriction;
import org.hibernate.annotations.SoftDelete;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.support.TransactionTemplate;

@SpringBootApplication
public class SoftDeleteTraps {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(SoftDeleteTraps.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        try (var context = app.run(args)) {
            ProductRepository products = context.getBean(ProductRepository.class);
            ArticleRepository articles = context.getBean(ArticleRepository.class);
            UserRepository users = context.getBean(UserRepository.class);
            OrderRepository orders = context.getBean(OrderRepository.class);
            TransactionTemplate tx = context.getBean(TransactionTemplate.class);

            System.out.println("1. deleteAllInBatch() with @SQLDelete");
            products.saveAll(List.of(new Product("pen"), new Product("ink")));
            products.deleteAllInBatch();
            System.out.println("   rows left in table: " + products.countAllRows());

            System.out.println("2. deleteAllInBatch() with @SoftDelete");
            articles.saveAll(List.of(new Article("a"), new Article("b")));
            articles.deleteAllInBatch();
            System.out.println("   rows left in table: " + articles.countAllRows()
                    + ", visible: " + articles.count());

            System.out.println("3. A unique column after soft delete");
            AppUser ann = users.save(new AppUser("ann@example.com"));
            users.delete(ann);
            try {
                users.save(new AppUser("ann@example.com"));
                System.out.println("   saved again");
            } catch (RuntimeException e) {
                System.out.println("   " + e.getClass().getSimpleName());
            }

            System.out.println("4. A reference to a soft-deleted row");
            AppUser bob = users.save(new AppUser("bob@example.com"));
            Long orderId = orders.save(new PurchaseOrder(bob)).getId();
            users.delete(bob);
            tx.executeWithoutResult(status -> System.out.println("   order.getUser() = "
                    + orders.findById(orderId).orElseThrow().getUser()));
            System.out.println("   order's user_id column = " + orders.userIdColumn(orderId));
        }
    }
}

@Entity
@SQLDelete(sql = "UPDATE product SET deleted = TRUE WHERE id = ?")
@SQLRestriction("deleted = FALSE")
class Product {
    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private boolean deleted;

    protected Product() {
    }

    Product(String name) {
        this.name = name;
    }
}

@Entity
@SoftDelete
class Article {
    @Id
    @GeneratedValue
    private Long id;
    private String title;

    protected Article() {
    }

    Article(String title) {
        this.title = title;
    }
}

@Entity
@SoftDelete
class AppUser {
    @Id
    @GeneratedValue
    private Long id;
    @Column(unique = true)
    private String email;

    protected AppUser() {
    }

    AppUser(String email) {
        this.email = email;
    }

}

@Entity
class PurchaseOrder {
    @Id
    @GeneratedValue
    private Long id;
    @ManyToOne
    private AppUser user;

    protected PurchaseOrder() {
    }

    PurchaseOrder(AppUser user) {
        this.user = user;
    }

    Long getId() {
        return id;
    }

    AppUser getUser() {
        return user;
    }
}

interface ProductRepository extends JpaRepository<Product, Long> {
    @Query(value = "SELECT COUNT(*) FROM product", nativeQuery = true)
    long countAllRows();
}

interface ArticleRepository extends JpaRepository<Article, Long> {
    @Query(value = "SELECT COUNT(*) FROM article", nativeQuery = true)
    long countAllRows();
}

interface UserRepository extends JpaRepository<AppUser, Long> {
}

interface OrderRepository extends JpaRepository<PurchaseOrder, Long> {
    @Query(value = "SELECT user_id FROM purchase_order WHERE id = ?1", nativeQuery = true)
    Long userIdColumn(Long id);
}
Output
1. deleteAllInBatch() with @SQLDelete
   rows left in table: 0
2. deleteAllInBatch() with @SoftDelete
   rows left in table: 2, visible: 0
3. A unique column after soft delete
   DataIntegrityViolationException
4. A reference to a soft-deleted row
   order.getUser() = null
   order's user_id column = 3
  • Case 1: deleteAllInBatch() runs one JPQL delete from Product statement instead of removing entities one by one. @SQLDelete only replaces the delete of a single entity, so the bulk statement really deleted both rows: 0 left. The same happens with @Modifying @Query("delete ...") and deleteAllByIdInBatch.
  • Case 2: with @SoftDelete, Hibernate also rewrites bulk deletes, so the same call kept both rows and only flagged them: 2 in the table, 0 visible. This is the strongest reason to prefer @SoftDelete in new code.
  • Case 3: the deleted user still occupies ann@example.com in the unique column, so signing up again with the same email failed with DataIntegrityViolationException. Fix it with a partial unique index on databases that support one, such as PostgreSQL's CREATE UNIQUE INDEX ... WHERE deleted = false, or by making the deletion timestamp part of the unique key.
  • Case 4: the order points to Bob, who was soft-deleted. Loading the order gave getUser() = null, with no exception, although the user_id column still holds Bob's id (3; id 2 was used up by the failed insert in case 3). Code that treats a null user as "guest" will now misreport old orders.

Case 4 is a design question as much as a bug: should an order of a deleted user show that user? Usually yes, and then the user should not be soft-deleted with an entity-level restriction at all. Instead, give the user a status, or load it with a native query that ignores the flag.

Showing deleted rows on demand with @Filter

@SQLRestriction and @SoftDelete apply always, which makes admin screens like "recently deleted" hard to build. A Hibernate filter is a named condition that is off until a session switches it on, and it can take parameters. One invoice of three is already marked deleted:

Java
package soft.filter;

import jakarta.persistence.Entity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.Id;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import org.hibernate.Session;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.support.TransactionTemplate;

@SpringBootApplication
public class FilterToggle {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(FilterToggle.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (var context = app.run(args)) {
            InvoiceRepository invoices = context.getBean(InvoiceRepository.class);
            EntityManager em = context.getBean(EntityManager.class);
            TransactionTemplate tx = context.getBean(TransactionTemplate.class);
            Invoice paid = new Invoice("INV-1");
            paid.markDeleted();
            invoices.saveAll(List.of(paid, new Invoice("INV-2"), new Invoice("INV-3")));
            Long deletedId = paid.getId();

            Supplier<String> report = () -> "findAll = " + invoices.findAll()
                    + ", findById(INV-1) present = " + invoices.findById(deletedId).isPresent();

            System.out.println("Filter off   : " + tx.execute(status -> report.get()));
            System.out.println("Active only  : " + tx.execute(status -> {
                em.unwrap(Session.class).enableFilter("deleted").setParameter("deleted", false);
                return report.get();
            }));
            System.out.println("Deleted only : " + tx.execute(status -> {
                em.unwrap(Session.class).enableFilter("deleted").setParameter("deleted", true);
                return report.get();
            }));
        }
    }
}

@Entity
@FilterDef(name = "deleted", parameters = @ParamDef(name = "deleted", type = Boolean.class))
@Filter(name = "deleted", condition = "deleted = :deleted")
class Invoice {
    @Id
    @GeneratedValue
    private Long id;
    private String number;
    private boolean deleted;

    protected Invoice() {
    }

    Invoice(String number) {
        this.number = number;
    }

    Long getId() {
        return id;
    }

    void markDeleted() {
        deleted = true;
    }

    @Override
    public String toString() {
        return number;
    }
}

interface InvoiceRepository extends JpaRepository<Invoice, Long> {
}
Output
Filter off   : findAll = [INV-1, INV-2, INV-3], findById(INV-1) present = true
Active only  : findAll = [INV-2, INV-3], findById(INV-1) present = true
Deleted only : findAll = [INV-1], findById(INV-1) present = true
  • With the filter off, findAll returned all three invoices.
  • Enabling the filter with deleted = false hid INV-1, and with deleted = true it showed only INV-1. One mapping serves both the normal view and the admin view.
  • In every case, findById still found INV-1. Filters apply to queries, not to loading an entity by id with EntityManager.find, which is what findById uses. A user who guesses an id can still reach a filtered row.

The filter is enabled on the Hibernate Session behind the current transaction's EntityManager, so it lasts only for that transaction. Applications that use filters for soft delete usually enable them in one place, such as an aspect around service methods or a web interceptor. Because of the findById gap, add an explicit check wherever an id comes from the user.

Soft delete and the rest of the application

  • Cascades: with CascadeType.REMOVE or orphanRemoval, deleting a parent removes its children one by one, and each child uses its own entity's delete. Children without soft delete annotations are hard-deleted.
  • Collections: an entity-level restriction also applies when Hibernate loads a collection of that entity, so a soft-deleted book disappears from its author's books list as well.
  • Who deleted it: @SQLDelete can set more columns, but its statement only receives the id (and the version, for a versioned entity). To record the user, set a deletedBy field and save the entity just before deleting it, or do the soft delete as an ordinary update in a service method. Auditing then fills the modified fields.
  • Indexes: most queries now include the flag. On large tables, add it to the indexes that queries use, or use partial indexes where the database supports them.
  • Purging: rows marked deleted still take space and still hold personal data. Plan a scheduled job that hard-deletes rows older than the retention period, with a native statement so the soft delete does not intercept it.

Choosing a soft delete design

Which approach fits which need
NeedUse
New code, a simple deleted flag or deletion time@SoftDelete, with TIMESTAMP if the time matters
Extra columns set on delete, or an existing schema@SQLDelete with @SQLRestriction, and no bulk deletes
Deleted rows shown in some screens@Filter, enabled per transaction, plus checks on loads by id
Rows that other data still refers to, such as users on ordersA status column and explicit queries, not an entity-level restriction
Full history of every changeHibernate Envers or an audit table, rather than soft delete alone
Data that must really be erasedA hard delete, or a purge job after the retention period

Whatever you choose, test the bulk paths and the native queries, because that is where soft delete quietly stops applying. The basics of delete and deleteAllInBatch are on the Spring Data JPA page, and the advanced page covers loading associations.