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 = ?UPDATE
The hard part is not the UPDATEand deleted = false
| Approach | Since | How it works | Best for |
|---|---|---|---|
@SQLDelete@SQLRestriction | @SQLRestriction@Where | You write the UPDATE | Custom columns, extra fields such as deleted_by |
@SoftDelete | Hibernate 6.4; TIMESTAMP | Hibernate manages a column and writes both the update and the condition | New code: less to write, and bulk deletes are handled too |
@Filter | Hibernate 3 | A condition switched on per session, with parameters | Admin views that show deleted rows on demand |
| Explicit status column | Any | Queries filter by status themselves | Rows that are archived rather than deleted, and still shown somewhere |
All of these work below Spring Data: the repository still calls EntityManager.remove
@SQLDelete with @SQLRestriction
This is the classic setup: a boolean deleted@SQLDelete@SQLRestriction
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);
}
-- 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
loaded Bob, then ran the customdeleteById instead of aUPDATE customer SET deleted = TRUE . The statement text is exactly what the annotation says.DELETE- Every following query, including
andfindById , hadcount added to its(deleted = false) clause. Bob is gone fromwhere ,findAll returns empty, and the count is 2.findById - The native query saw all three rows, with Bob flagged. Native SQL is passed to the database unchanged, so
does not apply to it.@SQLRestriction - Restoring needs a native
for the same reason in reverse: JPQL and repository methods cannot even find Bob any more. After it, Bob is back inUPDATE .findAll
The restriction is plain SQL, pasted into every query of the entity, so it must use column names, not field names. @SQLRestriction@Where@Where(clause = "deleted = false")
Hibernate's @SoftDelete
@SoftDeletedeletedTIMESTAMP
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();
}
-- 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
. The extraupdate note set deleted=true where id=? and deleted=false means a second delete of the same row changes nothing.and deleted=false - Queries got
, so only "buy milk" is listed. Thewhere n1_0.deleted=false class has noNote field at all; the column exists only in the table, as the native query shows.deleted - With
, the column holdsTIMESTAMP for live rows and the deletion time for deleted ones. The delete set it tonull , and queries filtered onlocaltimestamp .deleted is null
Other strategies and options: SoftDeleteType.ACTIVEactivetruecolumnNameconverter'Y''N'
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:
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);
}
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:
runs one JPQLdeleteAllInBatch() statement instead of removing entities one by one.delete from Product only replaces the delete of a single entity, so the bulk statement really deleted both rows: 0 left. The same happens with@SQLDelete and@Modifying @Query("delete ...") .deleteAllByIdInBatch - Case 2: with
, 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.@SoftDelete - Case 3: the deleted user still occupies
in the unique column, so signing up again with the same email failed withann@example.com . Fix it with a partial unique index on databases that support one, such as PostgreSQL'sDataIntegrityViolationException , or by making the deletion timestamp part of the unique key.CREATE UNIQUE INDEX ... WHERE deleted = false - Case 4: the order points to Bob, who was soft-deleted. Loading the order gave
, with no exception, although thegetUser() = null column still holds Bob's id (3; id 2 was used up by the failed insert in case 3). Code that treats auser_id user as "guest" will now misreport old orders.null
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@SoftDelete
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> {
}
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,
returned all three invoices.findAll - Enabling the filter with
hid INV-1, and withdeleted = false it showed only INV-1. One mapping serves both the normal view and the admin view.deleted = true - In every case,
still found INV-1. Filters apply to queries, not to loading an entity by id withfindById , which is whatEntityManager.find uses. A user who guesses an id can still reach a filtered row.findById
The filter is enabled on the Hibernate SessionEntityManagerfindById
Soft delete and the rest of the application
- Cascades: with
orCascadeType.REMOVE , 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.orphanRemoval - 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
list as well.books - Who deleted it:
can set more columns, but its statement only receives the id (and the version, for a versioned entity). To record the user, set a@SQLDelete field and save the entity just before deleting it, or do the soft delete as an ordinary update in a service method.deletedByAuditing 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
| Need | Use |
|---|---|
| New code, a simple deleted flag or deletion time | @SoftDeleteTIMESTAMP |
| Extra columns set on delete, or an existing schema | @SQLDelete@SQLRestriction |
| Deleted rows shown in some screens | @Filter |
| Rows that other data still refers to, such as users on orders | A status column and explicit queries, not an entity-level restriction |
| Full history of every change | Hibernate Envers or an audit table, rather than soft delete alone |
| Data that must really be erased | A 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 deletedeleteAllInBatch