Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

How would you add a soft-delete or tenant filter behaviour to all repositories in a service? Compare a custom base repository class with Hibernate filters and other options.

A custom base repository class can change the built-in methods such as findAll() and deleteById(), but it never touches derived query methods or @Query methods, so on its own it leaves gaps. Hibernate filters, @SQLRestriction and @TenantId push the condition into the SQL Hibernate generates, and database row-level security enforces it below the application for every client. In practice we combine a Hibernate-level mechanism with tests on every query path, and add row-level security where a leak would be serious.

Why this question is asked

Soft delete (marking a row as deleted instead of removing it) and multi-tenancy (many customers sharing one set of tables, separated by a tenant_id column) have the same shape: every query must carry an extra condition, and forgetting it once is a bug that shows deleted data or, worse, another customer's data. Interviewers ask this design question because the obvious answer, a custom base repository, only covers part of the problem, and they want to see whether we know where each mechanism stops working. In this answer, we will recap how Spring Data runs repository methods, look at the custom base class and its limits, then Hibernate filters, @SQLRestriction and @SoftDelete, Hibernate's @TenantId, database row-level security, and finally how to test that nothing slips through.

1A Quick Recap of How Spring Data Runs Repository Methods

When we declare an interface such as OrderRepository extends JpaRepository<Order, Long>, Spring Data generates a proxy for it at startup. Calls to built-in methods like findById(), findAll() or deleteById() are forwarded to a base class, SimpleJpaRepository by default, which holds the real implementation.

Methods we declare ourselves take a different route. A derived query method, such as findByCustomerId(Long id), is parsed from its name into a JPQL query by a component called PartTreeJpaQuery. A method with @Query runs the JPQL or native SQL we wrote. Neither of these goes through the base class, and that decides how far a custom base class can take us.

2Option 1: A Custom Base Repository Class

We can replace SimpleJpaRepository with our own subclass and register it for every repository in the application. Here is a soft-delete version that turns delete into an update and filters findAll().

Java
public class SoftDeleteRepository<T extends SoftDeletable, ID> extends SimpleJpaRepository<T, ID> {
private final EntityManager em;
public SoftDeleteRepository(JpaEntityInformation<T, ?> info, EntityManager em) {
super(info, em);
this.em = em;
}
@Override @Transactional
public void delete(T entity) {
entity.setDeleted(true); // UPDATE ... SET deleted = true, not DELETE
em.merge(entity);
}
@Override
public List<T> findAll() {
return findAll((root, q, cb) -> cb.isFalse(root.get("deleted"))); // only live rows
}
}
@EnableJpaRepositories(repositoryBaseClass = SoftDeleteRepository.class)
class JpaConfig {}
orderRepository.findAll(); // filtered: deleted rows hidden
orderRepository.findByCustomerId(42L); // NOT filtered: derived query bypasses the base class

Notice the last line. The derived query is built from the method name and executed without ever calling our findAll(), so deleted orders come back. The same is true for every @Query method and any JPQL run on the EntityManager. The base class is a good place for behaviour of the built-in methods, such as turning delete into an update, but it cannot be the only guard.

3Option 2: Hibernate Filters, @SQLRestriction and @SoftDelete

Hibernate can add the condition itself, at the point where it generates SQL. A filter is a named condition we declare on the entity and switch on per session, with a parameter. Because Hibernate applies it when it renders queries, it covers derived queries, @Query JPQL, criteria queries and collection loading alike.

Java
@Entity
@FilterDef(name = "tenant", parameters = @ParamDef(name = "tenantId", type = String.class))
@Filter(name = "tenant", condition = "tenant_id = :tenantId")
class Order { ... }
// at the start of each request, for example in a transactional aspect
Session session = entityManager.unwrap(Session.class);
session.enableFilter("tenant").setParameter("tenantId", "acme");
orderRepository.findByCustomerId(42L); // SQL: ... where customer_id = ? and tenant_id = ?
entityManager.find(Order.class, 7L); // check your version: loads by id ignored filters in older releases

There is a catch with filters: they must be enabled on every session, and if the code that enables them does not run (a scheduled job, an async thread, a new entry point) the filter is simply off and every row is visible. Loading by primary key also ignored filters in older Hibernate versions, and native SQL is never filtered.

For a fixed condition such as soft delete, a filter is more than we need. @SQLRestriction("deleted = false"), added in Hibernate 6.3 to replace the older @Where, is always on and applies to queries and associations. Hibernate 6.4 went further with @SoftDelete, which also turns remove() into an update of a deleted column. Annotation names and options have moved between versions, so check your version before choosing.

4Option 3: Hibernate's @TenantId

For discriminator-based multi-tenancy, where all tenants live in the same tables and a column tells them apart, Hibernate 6 offers @TenantId. We mark the tenant column on the entity and give Hibernate a CurrentTenantIdentifierResolver that returns the current tenant, typically from a request-scoped context.

Java
@Entity
class Order {
@Id Long id;
@TenantId String tenantId; // set automatically on insert, added to every query
}
// hibernate.tenant_identifier_resolver points at our resolver bean
class RequestTenantResolver implements CurrentTenantIdentifierResolver<String> {
public String resolveCurrentTenantIdentifier() { return TenantContext.current(); } // "acme"
public boolean validateExistingCurrentSessions() { return true; }
}

The advantage over a filter is that Hibernate cannot forget it: the tenant is fixed when the session opens, inserts get the value automatically, and a session cannot be switched to another tenant halfway. It still does not cover native SQL or other programs that use the same database.

5Option 4: Row-Level Security in the Database

Every option so far lives in the application. Row-level security moves the rule into the database itself. In PostgreSQL we enable it on the table and write a policy that compares the row's tenant with a setting our application sets on each transaction.

SQL
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY; -- apply it to the table owner too
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id'));
SELECT set_config('app.tenant_id', 'acme', true); -- true: only for this transaction
SELECT count(*) FROM orders; -- 120: only acme's rows, whatever the query
Where each option stops
OptionCoversMisses
Custom base repositoryBuilt-in methods: findAll, deleteDerived queries, @Query, raw JPQL, native SQL
Hibernate @FilterAll HQL, JPQL, criteria, collectionsSessions where it was not enabled, native SQL
@SQLRestriction / @SoftDeleteEvery Hibernate query and associationNative SQL; check your version for details
@TenantIdInserts and queries for the session's tenantNative SQL, other clients of the database
Row-level securityEvery client and every querySuperusers, and a wrong tenant setting
Each layer down covers more paths but costs more to operate.

Now even a hand-written native query, a reporting tool or a support engineer using the application's role sees only one tenant. The cost is operational: the setting must be applied on every transaction from the pool, superusers bypass policies, and query plans must be checked because the policy adds a condition to everything.

6Testing Every Query Path

Whichever combination we pick, the risk is a path we did not think about, and a missing filter leaks data silently. So the tests must try to leak. We seed two tenants, or a live row and a deleted row, then call every repository method and every endpoint that reads data while logged in as one tenant, and assert that nothing from the other tenant comes back.

A good pattern is a test that uses reflection to list every method on every repository interface, so a new query method without a test fails the build. We also include async jobs and scheduled tasks, because those are exactly the code paths where request-scoped context, and with it the filter, is missing.

7Follow-up questions

Why not just add a deleted = false condition to every query by hand?

Because it depends on every developer remembering it on every new query, forever. It works on the day it is written and breaks the first time someone adds a derived query method. Mechanisms that sit below the query, in Hibernate or in the database, remove that dependency on memory.

Does a unique constraint still work with soft delete?

Not directly. If email must be unique and a deleted row keeps its email, a new user cannot reuse it. In PostgreSQL we use a partial unique index such as CREATE UNIQUE INDEX ON users(email) WHERE NOT deleted, so only live rows take part in the uniqueness check.

Which would you choose for a SaaS product with strict tenant isolation?

I would use Hibernate @TenantId so the application gets it right by default, and PostgreSQL row-level security as a second line of defence, because a cross-tenant leak is a security incident rather than a bug. For soft delete alone, @SQLRestriction or @SoftDelete is usually enough.

8Conclusion

In this answer, we saw that a custom base repository class changes only the built-in repository methods, so derived and @Query methods slip past it. Hibernate filters, @SQLRestriction and @SoftDelete add the condition wherever Hibernate generates SQL, @TenantId fixes the tenant for the whole session, and row-level security enforces the rule in the database for every client. Because one missed path leaks data, we test every query path with two tenants or with deleted rows in place.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start by separating what each mechanism can actually cover. A custom base class registered with repositoryBaseClass on @EnableJpaRepositories is fine for changing built-in methods, for example turning delete into an update of a deleted flag, but derived query methods and @Query methods never go through it, so it cannot be the guard on its own.

Then, if they want more

For soft delete I would use Hibernate's @SQLRestriction, which replaced @Where in 6.3, or @SoftDelete in 6.4 and later, depending on the version we run. For tenants, a Hibernate filter works but must be enabled on every session, and the risk is the job or async thread where nobody enabled it.

So I prefer @TenantId with a CurrentTenantIdentifierResolver, because Hibernate sets the column on insert and restricts every query for that session. None of these cover native SQL or other clients, so if isolation is a security requirement I would add PostgreSQL row-level security with a policy on a per-transaction setting.

Finally, I would write tests that seed two tenants and call every repository method and endpoint, because a missing filter fails silently and only a test that tries to leak will catch it.

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 "How would you add a soft-delete or tenant filter behaviour to all repositories in a...": https://scrivio-interview-library.netlify.app/databases/spring-data-jpa/885267ce0c/