Spring Data Rest: Return Resources of User

后端 未结 3 1899
一生所求
一生所求 2020-12-09 23:56

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

相关标签:
3条回答
  • 2020-12-10 00:46

    You better implement a Controller for several reasons:

    • Imagine your application has some sort of management interface to look through all shopping lists (smth like admin account)

    • Or you need to manipulate the shopping list in some cron-based job (where the uses is missing)

    • business rules in code is better for learning new project (i.e. not all junior programmers can cope with spring magic easily)

    Downsides to note:

    • you will have to mimic current behavior of spring serialization (you can use it on other side)
    0 讨论(0)
  • 2020-12-10 00:53

    I solved this issue recently, see Spring Data Rest Override Repositories (Controllers vs AOP)

    The most elegant solution that I found was using AOP, this sample with QueryDSL and Spring Data REST Repositories:

    @Aspect
    @Transactional
    @Component
    public class FilterProjectsAspect {
    
    @Pointcut("execution(*  com.xxx.ProjectRepository.findAll(..))")
        public void projectFindAll() {
        }
    
        @Around("projectFindAll()")
        public Object  filterProjectsByUser(final ProceedingJoinPoint pjp) throws Throwable {
    
            Object[] args = pjp.getArgs();
            for (int i = 0; i < args.length; i++) {
                if (args[i] instanceof Predicate) {
                    Predicate predicate=(Predicate) args[i];
                    BooleanExpression isProjectOwner =buildExpressionForUser()
                    predicate = ExpressionUtils.allOf(isProjectOwner, predicate);
                    args[i]=predicate;  //Update args
                }
            return pjp.proceed(args);
        }
    
    }
    
    0 讨论(0)
  • 2020-12-10 00:55

    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();   
    }
    
    0 讨论(0)
提交回复
热议问题