Beware: this question has been falsely marked as duplicate. Anyways I found a solution that I will add to my question below, as answers cannot be posted anymore on "duplicate" questions.
I want to transform the following sql
query into a JPA
query using querydsl
and spring-data-jpa:
SELECT DISTINCT age FROM `my_table`
WHERE firstname = 'john' AND lastname = 'doe'
GROUP BY age
ORDER BY COUNT(*) DESC
LIMIT 1
Currently I have the following, which just selects all entries by first+lastname:
public interface MyRepository extends JpaRepository<MyEntity, Long>, QueryDslPredicateExecutor<MyEntity> {
}
Usage:
@Autowired
private MyRepository dao;
//select * from my_table where firstname = ? and lastname = ?
BooleanExpression query = p.firstname.eq(firstname).and(p.lastname.eq(lastname));
dao.findAll(query);
//TODO how to add group, order and limit?
But I now want to group by age
field and select the age that occurs the most. But how can I add DISTINCT
, GROUP BY
, ORDER BY COUNT
and LIMIT
statements in the querydsl?
Solution: it's not possible directly using CrudRepository
, but still easy by using com.querydsl.jpa.impl.JPAQuery
as follows:
QPersonEntity p = QPersonEntity.person; //the querydsl definition
int age = new JPAQuery(em)
.select(p.age)
.from(p)
.where(p.firstname.eq(firstname).and(p.lastname.eq(lastname)))
.groupBy(p.age)
.orderBy(p.age.count().desc())
.limit(1)
.fetchOne();