Yannic Klem Yannic Klem - 28 days ago 10
Java Question

Spring Data Rest: Return Resources of User

I'm creating a simple CRUD-App (a shoppinglist) with Spring Boot and Spring Data Rest. I have a resource:

ShoppingItem
. Is there an easy way to only return the resources which belong to the user who send the request? (Multiple User support) So a User only get his own ShoppingItems and not every ShoppingItem.
Or do i have to implement a Controller by myself, where i do this?

I found Spring Data REST filtering data based on the user this approach for filtering resources based on the user, but this won't help me for the repository endpoint.

Thanks in advance

Answer Source

If you are using Spring security integration you can use ACL (maybe to heavy) or simple postFilter like following:

public interface ShoppingItemRepository extends CrudRepository<ShoppingItem, Long> {
    @PostFilter("filterObject.user.getId() == principal.id")
    @Override
    Iterable<ShoppingItem> findAll();   
}