[Querydsl] Querydsl JPA CRUD Usages

Querydsl JPA CRUD Usages

Querydsl defines a general statically typed syntax for querying on top of persisted domain model data. JDO and JPA are the primary integration technologies for Querydsl. This guide describes how to use Querydsl in combination with JPA.

Querydsl for JPA is an alternative to both JPQL and Criteria queries. It combines the dynamic nature of Criteria queries with the expressiveness of JPQL and all that in a fully typesafe manner.

Model and Query Type

Let’s assume that your project has the following domain type:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import javax.persistence.Entity;

@Entity
public class Customer {
private String firstName;
private String lastName;

public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}

public void setFirstName(String fn) {
firstName = fn;
}

public void setLastName(String ln) {
lastName = ln;
}
}

Querydsl will generate a query type with the simple name QCustomer into the same package as Customer. QCustomer can be used as a statically typed variable in Querydsl queries as a representative for the Customer type.

QCustomer has a default instance variable which can be accessed as a static field:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import static com.querydsl.core.types.PathMetadataFactory.*;

import com.querydsl.core.types.dsl.*;

import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;


/**
* QAgreement is a Querydsl query type for Agreement
*/
@Generated("com.querydsl.codegen.EntitySerializer")
public class QAgreement extends EntityPathBase<Agreement> {

private static final long serialVersionUID = 1026402638L;

public static final QAgreement agreement = new QAgreement("agreement");

public final QBase _super = new QBase(this);

public final StringPath firstName = createString("firstName");

//inherited
public final DateTimePath<java.util.Date> createdAt = _super.createdAt;

public final ComparablePath<java.util.UUID> id = createComparable("id", java.util.UUID.class);

public final StringPath lastName = createString("lastName");

//inherited
public final DateTimePath<java.util.Date> updatedAt = _super.updatedAt;

public QAgreement(String variable) {
super(Agreement.class, forVariable(variable));
}

public QAgreement(Path<? extends Agreement> path) {
super(path.getType(), path.getMetadata());
}

public QAgreement(PathMetadata metadata) {
super(Agreement.class, metadata);
}

}

Use query type:

1
QCustomer customer = QCustomer.customer;

Alternatively you can define your own Customer variables like this:

1
QCustomer customer = new QCustomer("myCustomer");

Read, Querying

The Querydsl JPA module supports both the JPA and the Hibernate API.

To use the JPA API you use JPAQuery instances for your queries like this:

1
2
// where entityManager is a JPA EntityManager
JPAQuery<?> query = new JPAQuery<Void>(entityManager);

If you are using the Hibernate API instead, you can instantiate a HibernateQuery like this:

1
2
// where session is a Hibernate session
HibernateQuery<?> query = new HibernateQuery<Void>(session);

Both JPAQuery and HibernateQuery implement the JPQLQuery interface.

For the examples of this chapter the queries are created via a JPAQueryFactory instance. JPAQueryFactory should be the preferred option to obtain JPAQuery instances.

For the Hibernate API HibernateQueryFactory can be used

To retrieve the customer with the first name Bob you would construct a query like this:

1
2
3
4
QCustomer customer = QCustomer.customer;
Customer bob = queryFactory.selectFrom(customer)
.where(customer.firstName.eq("Bob"))
.fetchOne();

The selectFrom call defines the query source and projection, the where part defines the filter and fetchOne tells Querydsl to return a single element. Easy, right?

To create a query with multiple sources you use the query like this:

1
2
3
QCustomer customer = QCustomer.customer;
QCompany company = QCompany.company;
query.from(customer, company);

And to use multiple filters use it like this

1
2
queryFactory.selectFrom(customer)
.where(customer.firstName.eq("Bob"), customer.lastName.eq("Wilson"));

Or like this

1
2
queryFactory.selectFrom(customer)
.where(customer.firstName.eq("Bob").and(customer.lastName.eq("Wilson")));

In native JPQL form the query would be written like this:

1
2
select customer from Customer as customer
where customer.firstName = "Bob" and customer.lastName = "Wilson"

If you want to combine the filters via “or” then use the following pattern

1
2
queryFactory.selectFrom(customer)
.where(customer.firstName.eq("Bob").or(customer.lastName.eq("Wilson")));

Using joins

Querydsl supports the following join variants in JPQL: inner join, join, left join and right join. Join usage is typesafe, and follows the following pattern:

1
2
3
4
5
6
7
QCat cat = QCat.cat;
QCat mate = new QCat("mate");
QCat kitten = new QCat("kitten");
queryFactory.selectFrom(cat)
.innerJoin(cat.mate, mate)
.leftJoin(cat.kittens, kitten)
.fetch();

The native JPQL version of the query would be

1
2
3
select cat from Cat as cat
inner join cat.mate as mate
left outer join cat.kittens as kitten

Another example

1
2
3
4
queryFactory.selectFrom(cat)
.leftJoin(cat.kittens, kitten)
.on(kitten.bodyWeight.gt(10.0))
.fetch();

With the following JPQL version

1
2
3
select cat from Cat as cat
left join cat.kittens as kitten
on kitten.bodyWeight > 10.0

General usage

Use the the cascading methods of the JPQLQuery interface like this

  • select: Set the projection of the query. (Not necessary if created via query factory)

  • from: Add the query sources here.

  • innerJoin, join, leftJoin, rightJoin, on: Add join elements using these constructs. For the join methods the first argument is the join source and the second the target (alias).

  • where: Add query filters, either in varargs form separated via commas or cascaded via the and-operator.

  • groupBy: Add group by arguments in varargs form.

  • having: Add having filters of the “group by” grouping as an varags array of Predicate expressions.

  • orderBy: Add ordering of the result as an varargs array of order expressions. Use asc() and desc() on numeric, string and other comparable expression to access the OrderSpecifier instances.

  • limit, offset, restrict: Set the paging of the result. Limit for max results, offset for skipping rows and restrict for defining both in one call.

Ordering

The syntax for declaring ordering is

1
2
3
4
QCustomer customer = QCustomer.customer;
queryFactory.selectFrom(customer)
.orderBy(customer.lastName.asc(), customer.firstName.desc())
.fetch();

which is equivalent to the following native JPQL

1
2
3
select customer 
from Customer as customer
order by customer.lastName asc, customer.firstName desc

Grouping

Grouping can be done in the following form

1
2
3
queryFactory.select(customer.lastName).from(customer)
.groupBy(customer.lastName)
.fetch();

Method groupBy must combine select methods.


which is equivalent to the following native JPQL

1
2
3
select customer.lastName
from Customer as customer
group by customer.lastName

Update and Save

Update clauses

Update clauses in Querydsl JPA follow a simple update-set/where-execute form. Here are some examples:

1
2
3
4
5
QCustomer customer = QCustomer.customer;
// rename customers named Bob to Bobby
queryFactory.update(customer).where(customer.name.eq("Bob"))
.set(customer.name, "Bobby")
.execute();
1
2
3
update customer 
set customer.name = 'Bobby'
where customer.name = 'Bob'

The set invocations define the property updates in SQL-Update-style and the execute call performs the Update and returns the amount of updated entities.

DML clauses in JPA don’t take JPA level cascade rules into account and don’t provide fine-grained second level cache interaction.

Subqueries

To create a subquery you use the static factory methods of JPAExpressions and define the query parameters via from, where etc.

1
2
3
4
5
6
QDepartment department = QDepartment.department;
QDepartment d = new QDepartment("d");
queryFactory.selectFrom(department)
.where(department.size.eq(
JPAExpressions.select(d.size.max()).from(d)))
.fetch();

Another example

1
2
3
4
5
6
7
8
QEmployee employee = QEmployee.employee;
QEmployee e = new QEmployee("e");
queryFactory.selectFrom(employee)
.where(employee.weeklyhours.gt(
JPAExpressions.select(e.weeklyhours.avg())
.from(employee.department.employees, e)
.where(e.manager.eq(employee.manager))))
.fetch();

Exposing the original query

If you need to tune the original Query before the execution of the query you can expose it like this:

1
2
3
Query jpaQuery = queryFactory.selectFrom(employee).createQuery();
// ...
List results = jpaQuery.getResultList();

Using Native SQL in JPA queries

Querydsl supports Native SQL in JPA via the JPASQLQuery class.

To use it, you must generate Querydsl query types for your SQL schema. This can be done for example with the following Maven configuration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<project>
<build>
<plugins>
...
<plugin>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-maven-plugin</artifactId>
<version>${querydsl.version}</version>
<executions>
<execution>
<goals>
<goal>export</goal>
</goals>
</execution>
</executions>
<configuration>
<jdbcDriver>org.apache.derby.jdbc.EmbeddedDriver</jdbcDriver>
<jdbcUrl>jdbc:derby:target/demoDB;create=true</jdbcUrl>
<packageName>com.mycompany.mydomain</packageName>
<targetFolder>${project.basedir}/target/generated-sources/java</targetFolder>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>${derby.version}</version>
</dependency>
</dependencies>
</plugin>
...
</plugins>
</build>
</project>

When the query types have successfully been generated into the location of your choice, you can use them in your queries.

Single column query:

1
2
3
4
5
6
7
8
9
// serialization templates
SQLTemplates templates = new DerbyTemplates();
// query types (S* for SQL, Q* for domain types)
SAnimal cat = new SAnimal("cat");
SAnimal mate = new SAnimal("mate");
QCat catEntity = QCat.cat;

JPASQLQuery<?> query = new JPASQLQuery<Void>(entityManager, templates);
List<String> names = query.select(cat.name).from(cat).fetch();

If you mix entity (e.g. QCat) and table (e.g. SAnimal) references in your query you need to make sure that they use the same variable names. SAnimal.animal has the variable name “animal”, so a new instance (new SAnimal(“cat”)) was used instead.

An alternative pattern could be

1
2
QCat catEntity = QCat.cat;
SAnimal cat = new SAnimal(catEntity.getMetadata().getName());

Query multiple columns:

1
2
3
4
5
query = new JPASQLQuery<Void>(entityManager, templates);
List<Tuple> rows = query.select(cat.id, cat.name).from(cat).fetch();
Query all columns:

List<Tuple> rows = query.select(cat.all()).from(cat).fetch();

Query in SQL, but project as entity:

1
2
query = new JPASQLQuery<Void>(entityManager, templates);
List<Cat> cats = query.select(catEntity).from(cat).orderBy(cat.name.asc()).fetch();

Query with joins:

1
2
3
4
5
query = new JPASQLQuery<Void>(entityManager, templates);
cats = query.select(catEntity).from(cat)
.innerJoin(mate).on(cat.mateId.eq(mate.id))
.where(cat.dtype.eq("Cat"), mate.dtype.eq("Cat"))
.fetch();

Query and project into DTO:

1
2
3
4
5
query = new JPASQLQuery<Void>(entityManager, templates);
List<CatDTO> catDTOs = query.select(Projections.constructor(CatDTO.class, cat.id, cat.name))
.from(cat)
.orderBy(cat.name.asc())
.fetch();

If you are using the Hibernate API instead of the JPA API, then use HibernateSQLQuery instead.

References

[1] - https://querydsl.com/static/querydsl/latest/reference/html/ch02.html

[7] querydsl/querydsl: Unified Queries for Java - https://github.com/querydsl/querydsl

[8] Querydsl - Unified Queries for Java - https://querydsl.com/