Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Implement soft delete for a JPA entity Customer in Hibernate 6 so that repository.delete(customer) sets deleted_at instead of deleting, and normal queries hide deleted rows. What are the gotchas?

We annotate Customer with @SQLDelete(sql = "update customer set deleted_at = now() where id = ?") so that repository.delete runs an update, and with @SQLRestriction("deleted_at is null") so that entity loads and HQL hide deleted rows; Hibernate 6.4 and later also offers a built-in @SoftDelete. The gotchas are that native SQL ignores the restriction, associations pointing at a deleted row behave unexpectedly, a @Version column must be part of the custom delete SQL, and admin screens need a separate way to see deleted rows.

Why this question is asked

Teams usually want soft delete without changing every service method, so they ask the ORM to turn deletes into updates. Hibernate makes that easy, but the shortcut has sharp edges that only appear later, in a report built with native SQL or in an order that suddenly cannot load its customer. Interviewers ask this coding question to see both the mapping and the edges. In this answer, we will write the mapping, see what SQL Hibernate runs, look at the built-in @SoftDelete, and go through each gotcha with its fix.

1A Quick Recap of How Hibernate Deletes

When we call repository.delete(customer) in Spring Data JPA, it calls EntityManager.remove. Hibernate schedules a DELETE statement and runs it at flush time, usually at commit. Hibernate lets us replace that generated SQL with our own through @SQLDelete. It also lets us add a fixed SQL condition to every query that loads the entity through @SQLRestriction, the Hibernate 6.3 replacement for the older @Where annotation.

2Mapping Soft Delete on Customer

Here is the entity with both annotations.

Java
@Entity
@Table(name = "customer")
@SQLDelete(sql = "update customer set deleted_at = now() where id = ?")
@SQLRestriction("deleted_at is null")
public class Customer {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Instant deletedAt;
// getters and setters
}
Customer c = repository.save(new Customer("Ana")); // insert, id = 1
repository.delete(c); // update customer set deleted_at = now() where id = 1
repository.findById(1L); // Optional.empty
repository.count(); // 0
jdbc.queryForObject("select count(*) from customer", Long.class); // 1, the row is still there
Step throughWhat repository.delete(customer) runs
ServiceHibernateDatabase
repository.delete(customer)
schedule entity removal
flush: UPDATE ... SET deleted_at = now() WHERE id = 1
findById(1)
SELECT ... WHERE id = 1 AND (deleted_at is null)
no row
Optional.empty

7 messages in order. Play them, or step through them one at a time.

The ? in @SQLDelete is bound to the entity's id, the same parameter Hibernate would use for its own DELETE. The restriction is added to the SQL for find by id, HQL and JPQL queries, Criteria queries and the derived queries Spring Data builds, which is why findById and count no longer see the row. The last line shows the row is still in the table: plain JDBC knows nothing about the annotation.

3The Built-In @SoftDelete

Hibernate 6.4 added @SoftDelete, which does both jobs with one annotation. By default it uses a boolean column named deleted, and it can be configured with a different column name or with a converter for 'active' style flags. Later versions add a timestamp strategy so the column can record when the row was deleted (check your version for the exact options).

Java
@Entity
@SoftDelete // Hibernate 6.4+, boolean column "deleted"
public class Customer { @Id Long id; String name; }
// repository.delete(c) -> update Customer set deleted = true where id = ?
// queries -> ... where deleted = false

@SoftDelete also understands collections and is handled by Hibernate itself rather than by hand-written SQL, so there is no custom statement to keep in step with the mapping, such as the version placeholder discussed below. If the team needs a deleted_at timestamp on a Hibernate version without the timestamp strategy, the @SQLDelete approach remains the usual choice.

4Gotcha 1: Native Queries Ignore the Restriction

@SQLRestriction is applied to SQL that Hibernate generates. A native query is SQL we wrote, and Hibernate does not rewrite it.

Java
@Query(value = "select * from customer where name like :p", nativeQuery = true)
List<Customer> search(String p);
// returns deleted customers too, unless we add: and deleted_at is null

The fix is discipline plus help: add the condition to every native query, or point native queries at a view such as active_customer, and look for this in code review. Bulk JPQL updates and deletes are another place to check, since they also bypass entity-level handling.

5Gotcha 2: Associations to a Deleted Customer

Orders still have customer_id pointing at the soft-deleted row. What happens when an order loads its @ManyToOne customer depends on the mapping and Hibernate version. The restriction may not be applied to the to-one load, so the deleted customer appears as if alive, or it may be applied, in which case Hibernate finds no row and either throws an EntityNotFoundException or returns null if the association is mapped with @NotFound(action = NotFoundAction.IGNORE).

So we decide the behaviour on purpose. For orders, history matters, so we usually want the deleted customer to load and be shown as 'deleted customer'; that argues for not hiding the row from associations, and for filtering only in list queries. For something like a deleted coupon, refusing to load may be correct. Whatever we choose, an integration test that deletes a customer and then loads one of its orders keeps the behaviour from changing silently on an upgrade.

6Gotcha 3: Optimistic Locking and Admin Screens

If Customer has a @Version column, Hibernate's own DELETE includes the version in its WHERE clause, so a stale delete fails. Our custom SQL replaces that statement, and for a versioned entity Hibernate binds the id and then the version, so the SQL must include both placeholders or the binding fails and the version check is lost.

Java
@SQLDelete(sql = "update customer set deleted_at = now() where id = ? and version = ?")
public class Customer {
@Version private long version;
...
}
// stale delete: 0 rows updated -> OptimisticLockException (StaleObjectStateException underneath)

Finally, admin and audit screens must see deleted rows, and @SQLRestriction cannot be switched off. Those screens need a separate path: a native query, a read-only entity mapped to the same table without the restriction, or, if we choose a Hibernate @Filter instead of @SQLRestriction, a session where the filter is not enabled. A filter is opt-in per session, which makes it easier to bypass for admins but also easier to forget for normal code.

7Follow-up questions

When would you prefer an archive table instead?

When deleted rows are rarely read and the live table is hot. Moving the row to customer_archive in the same transaction as a real DELETE keeps the live table small, keeps unique constraints simple and makes 'deleted' a database fact that every query respects automatically. The cost is that restoring means copying back, and foreign keys from other tables must allow the parent to disappear, so it suits leaf data better than a customer with many references.

Does @SQLDelete still fire entity callbacks such as @PreRemove?

Yes, Hibernate still treats the operation as a removal, so lifecycle callbacks and the entity's removed state behave as for a normal delete; only the SQL is different. After the flush the entity is no longer managed in that persistence context.

How do unique constraints interact with this mapping?

Exactly as with any soft delete: the deleted row still holds its values, so a unique constraint on, say, email must become a partial unique index on live rows in PostgreSQL, or a generated-column trick in MySQL.

8Conclusion

In this answer, we mapped soft delete in Hibernate 6 with @SQLDelete to turn deletes into an update of deleted_at and @SQLRestriction to hide deleted rows from generated queries, and saw the built-in @SoftDelete from 6.4. We then went through the gotchas: native queries need the filter themselves, associations to deleted rows need a deliberate and tested behaviour, a @Version column must appear in the custom SQL, and admin screens need a separate query path.

What to say in the interviewAbout 90 seconds aloud

Open with

I would put two Hibernate annotations on the entity. @SQLDelete with sql update customer set deleted_at = now() where id = ?, which replaces the DELETE Hibernate would run, so repository.delete turns into an update.

Then, if they want more

And @SQLRestriction with deleted_at is null, the Hibernate 6.3 replacement for @Where, which is added to every query Hibernate generates for the entity: find by id, JPQL, criteria and Spring Data derived queries.

On Hibernate 6.4 and later there is also @SoftDelete, which does both with a boolean deleted column by default, and newer versions support a timestamp strategy; I would check the version. Then the gotchas. Native SQL queries are not rewritten, so they return deleted rows unless we add the condition or read from a view.

Associations are tricky: an order's @ManyToOne pointing at a deleted customer may load it anyway, or not find it and throw EntityNotFoundException, depending on mapping and version, so I decide what we want and pin it with an integration test.

If the entity has @Version, the custom SQL must be where id = ? and version = ?, because Hibernate binds both and the optimistic check is otherwise lost. And admin or audit screens need deleted rows, which @SQLRestriction cannot switch off, so they use a native query, a separate read-only mapping, or a Hibernate filter instead. Unique constraints also need partial indexes.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Implement soft delete for a JPA entity Customer in Hibernate 6 so that...": https://scrivio-interview-library.netlify.app/databases/data-modeling/272505b7a3/