Querydsl is a Java API for declaring and executing type-safe, portable database queries. It targets the same persistence problem as SQL, JPQL, Spring Data, and the JPA Criteria API while producing more readable query code than Criteria API. section 19.0 section 19.1
Maven’s annotation-processing step generates a Q-type for each JPA entity. Fields become typed paths such as StringPath and NumberPath<Long>; JPAQueryFactory then uses these paths to construct JPAQuery instances. section 19.2.1 section 19.3
Filtering and joining users
A username lookup combines a generated QUser path with a Predicate: queryFactory.selectFrom(QUser.user).where(QUser.user.username.eq("john")).fetchOne(). Multiple predicates compose with and or or. More advanced queries use JPAExpressions for subqueries and innerJoin, leftJoin, or outerJoin with on for joins. Hibernate translates these expressions into SQL. section 19.3.1 section 19.3.4
Use Querydsl with these operational boundaries:
- Execute database interactions inside EntityManager and transaction boundaries. section 19.3
- Treat bulk deletes carefully: JPA cascade rules and fine-grained second-level-cache behavior are not applied, so child entities may require explicit deletion first. section 19.3.6
- Use EntityManager, Hibernate Session, or Spring Data JPA repositories for inserts because Querydsl provides no insert capability. section 19.3.6
Listing 19.2 The pom.xml Maven file with the APT plugin
Path: Ch19/querydsl/pom.xml
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<outputDirectory>target/generated-sources/java</outputDirectory> #1
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor> #2
</configuration>
</execution>
</executions>
</plugin>
The Maven APT plugin configuration shows how generated Q-types are produced into target/generated-sources/java with the JPA annotation processor. section 19.2.1
