Hibernate Soft Delete: @SoftDelete Example and Strategies

Soft delete rows with Hibernate’s @SoftDelete: see the UPDATE that replaces DELETE, choose the DELETED, ACTIVE or TIMESTAMP strategy, read and restore deleted rows with native SQL, and avoid unique constraint errors.

logo

A soft delete keeps a row in its table and marks it as deleted, instead of removing it with a SQL DELETE. The data stays available for audits or an undo button, but the application no longer sees it.

We use soft delete when users expect to undo a delete, for example in a bookmark manager whose trash keeps deleted bookmarks for 30 days. Since version 6.4, Hibernate supports soft delete with the @SoftDelete annotation. The annotation adds an indicator column to the table and turns em.remove() into an UPDATE of that column. Hibernate also adds a filter on that column to every query, so deleted rows disappear from the application without leaving the database.

The following example marks the Bookmark entity for soft delete and shows the SQL for persist, remove, find and a query.

@Entity
@SoftDelete                     // adds the column: deleted boolean not null
public class Bookmark { ... }
em.persist(hotels);                             // insert into Bookmark (...,deleted,id) values (...,false,?)
em.remove(hotels);                              // update Bookmark set deleted=true where id=? and deleted=false
Bookmark found = em.find(Bookmark.class, id);   // null
List<Bookmark> live = em.createQuery("select b from Bookmark b", Bookmark.class)
    .getResultList();                           // select ... from Bookmark b1_0 where b1_0.deleted=false

Notice that em.find() returns null for the removed bookmark, although its row is still in the table.

Next, we compare soft and hard deletes and build a small bookmark manager with @SoftDelete. Along the way, we restore deleted rows, choose a strategy, soft delete collections and compare the annotation with the older @SQLDelete approach.

1. Soft Delete vs Hard Delete

A hard delete is the normal way of deleting an entity, where em.remove() sends a DELETE and the row is gone. With @SoftDelete, the same em.remove() call sends an UPDATE that flips the indicator column. Hibernate offers three strategies for that column.

  • DELETED (the default) stores true in a deleted column when the row is deleted.
  • ACTIVE stores true in an active column while the row is live, and false after the delete.
  • TIMESTAMP stores the time of the delete in a deleted column, and null while the row is live.
Grid of four cases for em.remove(): without @SoftDelete the SQL is delete from Bookmark where id=? and the row is gone; with the DELETED strategy the SQL is update Bookmark set deleted=true where id=? and deleted=false; with ACTIVE it is update Bookmark set active=false where id=? and active=true; with TIMESTAMP it is update BookmarkFolder set deleted=localtimestamp where id=? and deleted is null, and the row keeps the time of the delete
The Java code is the same in all four cases. Only the SQL and the row left behind change.

The difference shows up everywhere the row is read or written again.

OperationHard deleteSoft delete with @SoftDelete
em.remove(hotels)delete from Bookmark where id=?update Bookmark set deleted=true …
em.find() after the removenullnull
JPQL queryRow not foundRow skipped by the added deleted=false condition
Native SQL queryRow not foundRow found, with deleted = true
Undo the deleteImpossibleOne native UPDATE
Table sizeShrinksKeeps growing
Unique constraintsFree the valueStill hold the value (see section 4.1)

We use soft delete when deleted data must stay in the database, for example for a “Recently deleted” view or for rows that other tables still reference. When data must be erased from the database, for example after a user asks to delete their personal data, we still need a hard delete.

2. @SoftDelete Example

The following example is a browser bookmark manager built with Hibernate 7.4, Java 25 and an in-memory H2 database. The complete project on GitHub prints the SQL of each case and checks each result with 32 JUnit tests (mvn -q compile exec:java, mvn test).

2.1. Bookmark Folders and Bookmarks

A folder (“Work”, “Travel”) holds bookmarks such as “Hibernate Docs” or “Hotels”, and each bookmark has a set of tags. We soft delete all three levels.

  • Bookmark uses the default @SoftDelete, a boolean deleted column.
  • BookmarkFolder uses strategy = TIMESTAMP, so a folder in the trash keeps the time it was deleted.
  • The tags element collection has its own @SoftDelete, so a removed tag stays in the bookmark_tag table.
@Entity
@SoftDelete
public class Bookmark {

  @Id
  @GeneratedValue
  private Long id;

  private String title;
  private String url;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "folder_id")
  private BookmarkFolder folder;

  @ElementCollection
  @CollectionTable(name = "bookmark_tag", joinColumns = @JoinColumn(name = "bookmark_id"))
  @Column(name = "tag")
  @SoftDelete
  private Set<String> tags = new HashSet<>();
}
@Entity
@SoftDelete(strategy = SoftDeleteType.TIMESTAMP)
public class BookmarkFolder {

  @Id
  @GeneratedValue
  private Long id;

  private String name;

  @OneToMany(mappedBy = "folder", cascade = CascadeType.ALL)
  private List<Bookmark> bookmarks = new ArrayList<>();
}

There is no deleted field in either class. Hibernate owns the indicator column, which means Hibernate creates and maintains the column, and the entity never sees it. The generated schema shows the column on each table.

create table Bookmark (deleted boolean not null, folder_id bigint, id bigint not null, title varchar(255), url varchar(255), primary key (id))
create table bookmark_tag (deleted boolean not null, bookmark_id bigint not null, tag varchar(255), unique (bookmark_id, tag))
create table BookmarkFolder (deleted timestamp(6) with time zone, id bigint not null, name varchar(255), primary key (id))
comment on column Bookmark.deleted is 'Soft-delete indicator'

New rows get the “not deleted” value in the INSERT itself, which is false for a bookmark and null for a folder.

insert into BookmarkFolder (name,deleted,id) values (?,null,?)
insert into Bookmark (folder_id,title,url,deleted,id) values (?,?,?,false,?)
insert into bookmark_tag (bookmark_id,tag,deleted) values (?,?,false)

2.2. Removing an Entity

We remove the “H2 Database” bookmark the usual way. Hibernate first soft deletes the bookmark’s tags, then the bookmark.

emf.runInTransaction(em -> em.remove(em.find(Bookmark.class, h2Id)));
// update bookmark_tag set deleted=true where bookmark_id=? and deleted=false
// update Bookmark set deleted=true where id=? and deleted=false

No DELETE statement runs, and the and deleted=false condition limits the update to rows that are not deleted yet.

2.3. How find() and Queries Skip Deleted Rows

Every SQL that Hibernate generates for a soft-deleted entity carries the indicator condition. The condition appears in em.find() and in JPQL queries, including their joins.

Bookmark found = em.find(Bookmark.class, h2Id);
// select ... from Bookmark b1_0 where b1_0.deleted=false and b1_0.id=?
// null

List<Bookmark> bookmarks = em.createQuery("select b from Bookmark b order by b.title", Bookmark.class).getResultList();
// select ... from Bookmark b1_0 where b1_0.deleted=false order by b1_0.title
// [Hibernate Docs, Hotels, Train Times]

Long count = em.createQuery("select count(*) from Bookmark", Long.class).getSingleResult();   // 3

List<Object[]> rows = em.createQuery("select b.title, f.name from Bookmark b join b.folder f", Object[].class).getResultList();
// ... join BookmarkFolder f1_0 on f1_0.id=b1_0.folder_id and f1_0.deleted is null where b1_0.deleted=false

The join condition matters, because a bookmark whose folder is in the trash drops out of an inner join, even though the bookmark itself is not deleted.

2.4. Reading and Restoring Deleted Rows

JPQL has no switch to include deleted rows. To see or restore a soft-deleted row, we use native SQL queries, because Hibernate does not change SQL that we write ourselves. For example, a “Trash” page in the bookmark manager lists the deleted bookmarks with a native query.

Object total = em.createNativeQuery("select count(*) from Bookmark").getSingleResult();   // 4

List<Bookmark> trash = em.createNativeQuery("select * from Bookmark where deleted = true", Bookmark.class)
    .getResultList();                                                                    // [H2 Database]

Restoring is a native update that writes the “not deleted” value back. After the update, em.find() returns the bookmark again.

em.createNativeQuery("update Bookmark set deleted = false where id = ?")
    .setParameter(1, h2Id)
    .executeUpdate();

Bookmark restored = em.find(Bookmark.class, h2Id);   // H2 Database

A native query uses the column values of the chosen strategy, such as deleted = false for DELETED, active = true for ACTIVE and deleted = null for TIMESTAMP. Restoring a parent does not restore the children that were deleted with it. We restore them with a second update.

em.createNativeQuery("update BookmarkFolder set deleted = null where id = ?")
    .setParameter(1, travelId).executeUpdate();
List<Bookmark> before = em.find(BookmarkFolder.class, travelId).getBookmarks();   // []

em.createNativeQuery("update Bookmark set deleted = false where folder_id = ?")
    .setParameter(1, travelId).executeUpdate();
List<Bookmark> after = em.find(BookmarkFolder.class, travelId).getBookmarks();    // [Train Times, Hotels]

2.5. Choosing the Strategy, Column Name and Stored Values

@SoftDelete has three attributes that decide what the indicator column looks like.

AttributeDefaultWhat it changes
strategyDELETEDDELETED, ACTIVE or TIMESTAMP
columnNamedeleted (active for ACTIVE)Name of the indicator column
converterBoolean column of the databaseHow true and false are stored

With strategy = ACTIVE, live rows hold true and the update flips it to false.

@SoftDelete(strategy = SoftDeleteType.ACTIVE)

em.persist(hotels);   // insert into Bookmark (title,url,active,id) values (?,?,true,?)
em.remove(hotels);    // update Bookmark set active=false where id=? and active=true

The attributes columnName and converter fit an existing table, for example a legacy removed CHAR(1) column with ‘Y’ and ‘N’.

@SoftDelete(columnName = "removed", converter = YesNoConverter.class)

// create table Bookmark (removed char(1) not null check ((removed in ('N','Y'))), ...)
em.persist(hotels);   // insert into Bookmark (title,url,removed,id) values (?,?,'N',?)
em.remove(hotels);    // update Bookmark set removed='Y' where id=? and removed='N'

Hibernate ships three converters for the common cases. Any AttributeConverter<Boolean, X> works as well.

ConverterStored for trueStored for false
NumericBooleanConverter10
YesNoConverter‘Y’‘N’
TrueFalseConverter‘T’‘F’

The converter maps the boolean “deleted” or “active” value, and the strategy decides which one is stored. When we combine a converter with TIMESTAMP, Hibernate refuses to start.

org.hibernate.metamodel.UnsupportedMappingException: Specifying SoftDelete#converter in conjunction with SoftDeleteType.TIMESTAMP is not supported

We pick the strategy by what the table needs.

  • DELETED fits new tables.
  • ACTIVE fits an existing active column that already means “live”.
  • TIMESTAMP fits when we need to know when the row was deleted, for example to purge the trash after 30 days.

2.6. Deleting a Folder With Its Bookmarks

Soft delete works with cascade types. The folder’s @OneToMany has cascade = CascadeType.ALL, so removing the “Travel” folder calls remove() on each of its bookmarks, and each one is soft deleted with its own strategy.

emf.runInTransaction(em -> em.remove(em.find(BookmarkFolder.class, travelId)));
// update bookmark_tag set deleted=true where bookmark_id=? and deleted=false   (per bookmark)
// update Bookmark set deleted=true where id=? and deleted=false                (per bookmark)
// update BookmarkFolder set deleted=localtimestamp where id=? and deleted is null
Three tables after em.remove(travel): BookmarkFolder with Work deleted null and Travel deleted 2026-10-03 15:13; Bookmark with Hibernate Docs and H2 Database false and the Travel bookmarks Train Times and Hotels true; bookmark_tag with the Hibernate Docs tags java and docs false; a note says the cascade runs remove() for each bookmark and no row is removed
The folder gets a timestamp, its bookmarks get true. Every row is still in the database.

2.7. Soft Delete on a Collection

@SoftDelete on a collection field soft deletes the rows of the collection table. It works on @ElementCollection and @ManyToMany only, because both have a table that belongs to the collection. Removing the “docs” tag marks one row.

em.find(Bookmark.class, docsId).getTags().remove("docs");
// update bookmark_tag set deleted=true where bookmark_id=? and tag=? and deleted=false

// bookmark_tag rows: [docs, true], 
Set<String> tags = em.find(Bookmark.class, docsId).getTags();   // 

On a many-to-many association, the annotation marks the row in the join table and leaves the target entity alone. On @OneToMany, the rows belong to the child entity, so we put @SoftDelete on the child class instead. If we put it on the @OneToMany association itself, Hibernate fails at startup.

org.hibernate.metamodel.UnsupportedMappingException: @SoftDelete cannot be applied to @OneToMany - com.howtodoinjava.hibernate.softdelete.OneToManySoftDeleteFolder.bookmarks

2.8. Bulk Delete With JPQL

A JPQL delete statement on a soft-deleted entity also becomes an UPDATE, including the collection rows. The method executeUpdate() returns the number of soft-deleted rows.

int count = em.createQuery("delete from Bookmark where url like '%hibernate%'").executeUpdate();   // 1
// update bookmark_tag to_delete_ set deleted=true where to_delete_.bookmark_id in (select b1_0.id from Bookmark b1_0 where ... and b1_0.deleted=false)
// update Bookmark b1_0 set deleted=true where b1_0.url like '%hibernate%' escape '' and b1_0.deleted=false

3. @SoftDelete vs @SQLDelete and @SQLRestriction

Before Hibernate 6.4, we built soft delete from two annotations and a mapped field. The @SQLDelete annotation replaces the DELETE statement with our own SQL, and @SQLRestriction (called @Where until Hibernate 6.3) adds a SQL condition to every query.

@Entity
@SQLDelete(sql = "update Bookmark set deleted = true where id = ?")
@SQLRestriction("deleted = false")
public class Bookmark {
  ...
  private boolean deleted;
}
em.remove(hotels);                              // update Bookmark set deleted = true where id = ?
Bookmark found = em.find(Bookmark.class, id);   // ... where lb1_0.id=? and (lb1_0.deleted = false)   -> null
em.createQuery("delete from Bookmark where title = 'Train Times'").executeUpdate();
                                                // delete from Bookmark lb1_0 where ... (a real delete)

Both approaches hide deleted rows from find() and queries, so the differences are in the cases the hand-written SQL does not cover.

Comparison grid: em.remove() runs the generated update with @SoftDelete and the hand-written SQL with @SQLDelete; both filter find() and JPQL; a JPQL bulk delete becomes an update with @SoftDelete but is a real delete with @SQLDelete; the flag is not mapped with @SoftDelete and stays false in memory with @SQLDelete; @SoftDelete offers DELETED, ACTIVE and TIMESTAMP with converters, @SQLDelete any unchecked SQL; @SoftDelete needs 6.4, @SQLRestriction 6.3 and @Where was removed in 7.0
The JPQL bulk delete is the main trap of the older approach: it skips @SQLDelete and removes the rows for real.
Behavior@SoftDelete@SQLDelete + @SQLRestriction
em.remove()Generated UPDATEOur UPDATE from @SQLDelete
find(), JPQL, joinsFilteredFiltered
JPQL bulk deleteSoft (UPDATE)Hard DELETE
Flag in the entityNot mappedMapped, but stays false in memory after remove()
Column typesDELETED, ACTIVE, TIMESTAMP, convertersAny SQL, not checked by Hibernate
NeedsHibernate 6.4+Hibernate 6.3+ (@Where before)

For new code on Hibernate 6.4 or later, we use @SoftDelete. The older approach still makes sense when the delete must do more than set a flag, for example also write who deleted the row.

4. Soft Delete FAQs

4.1. Why Does Reusing a Deleted Name Fail With a Unique Constraint Error?

A soft-deleted row still holds its values, so it still takes part in every unique constraint. With @Column(unique = true) on the folder name, we cannot create a new “Travel” folder after deleting the old one.

jakarta.persistence.RollbackException: Error while committing the transaction [could not execute statement [Unique index or primary key violation: "PUBLIC.CONSTRAINT_3 INDEX PUBLIC.CONSTRAINT_INDEX_3 ON PUBLIC.BOOKMARKFOLDER(NAME NULLS FIRST) VALUES ( /* 1 */ 'Travel' )"; ...

The fix is a unique constraint that covers active rows only. With the TIMESTAMP strategy, every deleted row has its own timestamp and active rows have null, so a constraint on (name, deleted) that treats nulls as equal works. PostgreSQL 15+ and H2 2.x (H2 2.5.252 in our example) support NULLS NOT DISTINCT. We add the constraint in the schema migration script.

alter table BookmarkFolder add constraint uk_folder_name unique nulls not distinct (name, deleted);
Rows of BookmarkFolderAllowed?
“Travel” (deleted), “Travel” (deleted later), “Travel” (active)Yes
“Travel” (active), “Travel” (active)No, UK_FOLDER_NAME violation

The same constraint on a boolean deleted column does not work, because the second time a bookmark with the same URL is deleted, (url, true) already exists and the remove() fails.

Collections have the same problem. Hibernate makes (bookmark_id, tag) unique for a Set element collection, so adding a tag back after removing it fails with Unique index or primary key violation … BOOKMARK_TAG(BOOKMARK_ID NULLS FIRST, TAG NULLS FIRST). A List mapping has no such key, but Hibernate then rewrites the whole collection on every change and leaves a soft-deleted copy of each tag behind.

4.2. Why Is My LAZY @ManyToOne Loaded Right Away?

Bookmark.folder is mapped with FetchType.LAZY, yet em.find() runs a second SELECT for the folder.

Bookmark bookmark = em.find(Bookmark.class, h2Id);
// select ... from Bookmark b1_0 where b1_0.deleted=false and b1_0.id=?
// select bf1_0.id,bf1_0.name from BookmarkFolder bf1_0 where bf1_0.deleted is null and bf1_0.id=?

The folder_id column alone cannot tell Hibernate whether that folder is soft deleted, so it loads the folder to decide between an object and null. When the folder is in the trash, getFolder() returns null even though folder_id has a value. Lazy loading of a @ManyToOne only works when the target entity is not soft deleted. With a plain, non-soft-deleted folder entity, the same find() runs one SELECT.

4.3. Can I Read the Deleted Flag in My Entity?

Not in a useful way. We can map the column as a read-only field, but a loaded entity is always a live row, so the field always reads false.

@Column(name = "deleted", insertable = false, updatable = false)
private boolean deleted;    // always false: deleted rows are never loaded

To work with deleted rows, we load them with a native query as in section 2.4, or keep the older @SQLDelete approach with a mapped field.

4.4. What Replaced @Where in Hibernate 7?

The @SQLRestriction annotation replaced @Where. Hibernate 6.3 deprecated @Where and @WhereJoinTable, and Hibernate 7.0 removed them, together with @Loader. Old soft delete mappings with @SQLDelete and @Where need @SQLRestriction on Hibernate 7, or a move to @SoftDelete.

5. Conclusion

@SoftDelete turns em.remove() into an UPDATE of an indicator column and filters that column out of find(), JPQL, joins and bulk deletes. We choose the strategy (DELETED, ACTIVE or TIMESTAMP) per entity or collection, and adjust the column name and the stored values to fit an existing table.

We read and restore deleted rows with native SQL and design unique constraints so that deleted rows do not block new ones.

6. References

Happy Learning !!

Source Code on Github

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.