Search code examples
javaquerydsl

Querydsl: How to write a "complex" query


I'm trying to create an sql sentence using querydsl. What I'm trying to get is:

SELECT P.KEY, COUNT(P.VALUE)
 FROM RESOURCES R JOIN PROPERTIES P ON R.ID = P.ID
 WHERE P.KEY = "key" AND p.VALUE = "value"
 GROUP BY P.VALUE;

I've tried to write some querydsl code:

String s = queryFactory
    .query()
    .from(QResource.resource)
    .join(QProperty.property)
    .where(QResource.resource.properties.any().key.eq("key").and(QResource.resource.properties.any().value.eq("value")))
    .groupBy(QProperty.property.value)
    .select(QProperty.property.key, QProperty.property.value.count())
    .toString();

I'm guessing it can be simplified and by other hand I don't quite see if it's well querydsl-coded.

Any ideas?


Solution

  • A more simplified version would be:

    QResource r = QResource.resource;
    QProperty p = QProperty.property;
    queryFactory
        .select(p.key, p.value.count())
        .from(r)
        .join(p).on(r.id.eq(p.id))
        .where(p.key.eq("key"), p.value.eq("value"))
        .groupBy(p.value)
        .fetchOne();