Query filtering applies authorization criteria inside a database query so the data source returns only permitted records. In Spring Data repositories, this avoids loading unauthorized rows and filtering them afterward in application memory. section 12.3 section 12.4
Choose query filtering instead of repository-level postfiltering when:
- A repository method could retrieve many records, because postfiltering may create heavy memory and performance costs. section 12.3
- The permitted records can be expressed as a repository query condition, such as matching the current authentication name to an owner field. section 12.3
- Application-level filtering is unavoidable at the service layer, but repository filtering can retrieve only the required records at the source. section 12.3
Restrict products by authenticated owner
A ProductRepository query combines a name condition with `p.owner=?#{authentication.name}`. Searching for `c` returns candy to nikolai and chocolate to julien, without retrieving the other user's product for later filtering. section 12.3
Figure 12.10 In our scenario, we start by implementing the application using @PostFilter to filter products based on their owner. Then we change the implementation to add the condition directly on the query. This way, we make sure the application only gets from the source the needed records.
Compare repository postfiltering with adding the ownership condition directly to the query. section 12.3
