QueryDSL Predicate (Data JPA) which will query all the records by some rule and group them?

1.2k views Asked by At

If I have products table in my database and I want to query 20 most expensive products.

SELECT p FROM Products p ORDER BY p.price DESC LIMIT 20

How can I translate that to QueryDSL Predicate or is it even possible? I've read a lot of tutorials and other stuff and I've seen thing like this:

QProducts p = QProducts.product;
JPAQuery query = new JPAQuery(entityManager);
     query.from(p).orderBy(p.price.price.asc().limit(20));

I haven't used JPA EntityManager in my program so I don't know what to do. So far I've done only query's like this and they are working just fine without any EntityManager.

public static Predicate productName(String searchTerm){
     QProduct product = QProduct.product;
     return product.name.startsWithIgnoreCase(searchTerm);
}

I just pass that Predicate to method provided by Spring DATA JPA. How could I solve my problem described above with style like my previous predicate?

1

There are 1 answers

0
Simon On

No, orderBy and limit clauses cannot be part of a Predicate.

But as you're using Spring Data JPA you should have an EntityManager in your Spring context. Try to wire it into your custom repository like this:

@PersistenceContext
protected EntityManager em;