M.Haris Qayyum
M.Haris Qayyum

Reputation: 137

@Query not working with QueryDSL predicate

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

Upvotes: 2

Views: 2853

Answers (3)

M.Haris Qayyum
M.Haris Qayyum

Reputation: 137

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

Upvotes: 0

Jens Schauder
Jens Schauder

Reputation: 81907

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.

Upvotes: 1

PaolaG
PaolaG

Reputation: 814

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

Upvotes: 1

Related Questions