@Query not working with QueryDSL predicate

2019-07-10 14:25发布

I'm trying to use @Query over QueryDSL's Overrided method, but when i'm doing that, it is ignoring my predicate which i'm providing e.g. http://localhost:8080/orders?state=Texas

The reason i need @Query is to apply security based on authentication principal e.g.

@Query("select o from Orders o where ?#{principal.username} = o.username")

Complete code of repository:

public interface OrderRepository extends JpaRepository<Order, Integer>, QuerydslPredicateExecutor<Order>{

    @Override
    @Query("select o from Orders o where ?#{principal.username} = o.username")
    Page<Order> findAll(Predicate predicate, Pageable pageable);
}

3条回答
劳资没心,怎么记你
2楼-- · 2019-07-10 14:32

For anyone who also wants to embed some custom predicate in QueryDSL should look it once: https://github.com/yeldarxman/QueryDslPredicateModifier

查看更多
干净又极端
3楼-- · 2019-07-10 14:35

With QueryDSL predicates you can create a class for create the query, using query builder

Like this:

    public class OrderPredicates {

    private OrderPredicates() {

    }

     public static Predicate findByCriteria(OrderSearchCriteria orderSearchCriteria) {

            QOrder order = QOrder.order;
            BooleanBuilder builder = new BooleanBuilder();
           if(orderSearchCriteria.getUsername!=null){
            builder.or(order.username
                        .eq(orderSearchCriteria.getUsername));
           }

            //Some other predicates

            return builder;
        }
}

But if you want to extrat a list of Order by principal, you can create an ad-hoc query

First: Delete the override

Second: Define a query with an intuitive name

Third: use a parameter query

@Query("from Orders o where o.username = :username")
Page<Order> findAllByUser(@Param(value="username") String username, Pageable pageable);
查看更多
疯言疯语
4楼-- · 2019-07-10 14:35

You have to make up your mind if you want a method implemented based on a provided query or based on a QueryDSL predicate. Spring Data doesn't combine them (as you found out).

In this case, I assume you have a good reason to use QueryDSL, therefore you should just add the principal based constraint to that predicate.

This article shows how to access the principal which you can use wherever you are constructing your Querydsl predicate.

查看更多
登录 后发表回答