@Query not working with QueryDSL predicate

纵饮孤独 提交于 2019-12-23 23:14:55

问题


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);
}

回答1:


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);



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/52053074/query-not-working-with-querydsl-predicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!