Video in progress
To show rows depending on the user's permissions: Hibernate @Filter or database-level Row Level Security, which do you choose?
@Filter is convenient and lives inside the application, but forgetting to enable it, native SQL and a direct find by ID all bypass it. If the security requirement is serious, I make PostgreSQL RLS the main protection, and @Filter or @TenantId stays as a convenience layer.
📖 Answer
A Hibernate filter looks like this:
@Entity
@FilterDef(name = "region", parameters = @ParamDef(name = "regionId", type = Long.class))
@Filter(name = "region", condition = "region_id = :regionId")
class Branch { ... }
session.enableFilter("region").setParameter("regionId", currentUser.regionId());
Once the filter is enabled on the Session, it is added to HQL/Criteria queries and collection loads. But it has holes:
em.find(Branch.class, id)does not apply the filter: a user who knows the ID opens another region's record;- native SQL and bulk operations don't obey it;
- the filter has to be enabled in every Session; one forgotten place (a scheduled job, a new endpoint) and all the data is exposed;
- the L2 cache doesn't know about the filter.
PostgreSQL RLS:
alter table branch enable row level security;
create policy region_isolation on branch
using (region_id = current_setting('app.region_id')::bigint);
At the start of each transaction the application does set local app.region_id = ... (for example when the connection is acquired, or in a transaction listener). Now whatever SQL is written, the database filters on its own. Downsides: with a connection pool you must do set local in every transaction, migrations and admin work need a separate role (BYPASSRLS), and the planner sometimes picks a slower plan because of the policy.
The decision: for display convenience (for example, "hide archived rows"), @Filter. Where permissions and the risk of data leaking are involved, RLS is mandatory, and the application filter is a second layer.
Sign up to mark studied questions and save your progress.