Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Querydsl and JPA Criteria are popular frameworks for constructing type-safe queries in Java. They both provide ways to express queries statically typed, making it easier to write efficient and maintainable code for interacting with databases. In this article, we’ll compare them from various perspectives.

2. Setup

First, we need to set up dependencies and configurations for our tests. In all the examples, we’ll use HyperSQL Database:

<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <version>2.7.1</version>
</dependency>

We’ll use JPAMetaModelEntityProcessor and JPAAnnotationProcessor to generate metadata for our frameworks. For this purpose, we’ll add maven-processor-plugin with the following configuration:

<plugin>
    <groupId>org.bsc.maven</groupId>
    <artifactId>maven-processor-plugin</artifactId>
    <version>5.0</version>
    <executions>
        <execution>
            <id>process</id>
            <goals>
                <goal>process</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
                <processors>
                    <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
                    <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                </processors>
            </configuration>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <version>6.2.0.Final</version>
        </dependency>
    </dependencies>
</plugin>

Then, let’s configure properties for our EntityManager:

<persistence-unit name="com.baeldung.querydsl.intro">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <properties>
        <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
        <property name="hibernate.connection.url" value="jdbc:hsqldb:mem:test"/>
        <property name="hibernate.connection.username" value="sa"/>
        <property name="hibernate.connection.password" value=""/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
    </properties>
</persistence-unit>

2.1. JPA Criteria

To use the EntityManager, we need to specify dependencies for any JPA provider. Let’s choose a Hibernate as the most popular one:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>6.2.0.Final</version>
</dependency>

To support code generation functionality, we’ll add the Annotation Processor dependency:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-jpamodelgen</artifactId>
    <version>6.2.0.Final</version>
</dependency>

2.2. Querydsl

Since we’re going to use it with the EntityManager, we still need to include the dependency from the previous section. Additionally, we’ll incorporate Querydsl dependency:

<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-jpa</artifactId>
    <version>5.0.0</version>
</dependency>

To support code generation functionality, we’ll add APT based Source code generation dependency:

<dependency>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-apt</artifactId>
    <classifier>jakarta</classifier>
    <version>5.0.0</version>
</dependency>

3. Simple Queries

Let’s start with the simple queries to one entity without any additional logic. We’ll use the next data model, the root entity will be a UserGroup:

@Entity
public class UserGroup {
    @Id
    @GeneratedValue
    private Long id;

    private String name;

    @ManyToMany(cascade = CascadeType.PERSIST)
    private Set<GroupUser> groupUsers = new HashSet<>();

    // getters and setters
}

In this entity, we’ll establish a many-to-many relationship with a GroupUser:

@Entity
public class GroupUser {
    @Id
    @GeneratedValue
    private Long id;

    private String login;

    @ManyToMany(mappedBy = "groupUsers", cascade = CascadeType.PERSIST)
    private Set<UserGroup> userGroups = new HashSet<>();

    @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "groupUser")
    private Set<Task> tasks = new HashSet<>(0);
 
    // getters and setters
}

And, finally, we’ll add a Task entity that relates many-to-one to our User:

@Entity
public class Task {
    @Id
    @GeneratedValue
    private Long id;

    private String description;

    @ManyToOne
    private GroupUser groupUser;
    // getters and setters
}

3.1. JPA Criteria

Now, let’s select all the UserGroup items from the database:

@Test
void givenJpaCriteria_whenGetAllTheUserGroups_thenExpectedNumberOfItemsShouldBePresent() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<UserGroup> cr = cb.createQuery(UserGroup.class);
    Root<UserGroup> root = cr.from(UserGroup.class);
    CriteriaQuery<UserGroup> select = cr.select(root);

    TypedQuery<UserGroup> query = em.createQuery(select);
    List<UserGroup> results = query.getResultList();
    Assertions.assertEquals(3, results.size());
}

We created an instance of CriteriaBuilder by calling the getCriteriaBuilder() method of EntityManager. Then, we created an instance of CriteriaQuery for our UserGroup model. After that, we obtained an instance of TypedQuery by calling the EntityManager createQuery() method. By calling the getResultList() method, we retrieved the list of entities from the database. As we can see, the expected number of items is present in the result collection.

3.2. Querydsl

Let’s prepare the JPAQueryFactory instance, which we’ll use to create our queries.

@BeforeEach
void setUp() {
    em = emf.createEntityManager();
    em.getTransaction().begin();
    queryFactory = new JPAQueryFactory(em);
}

Now, we’ll perform the same query as in the previous section using Querydsl:

@Test
void givenQueryDSL_whenGetAllTheUserGroups_thenExpectedNumberOfItemsShouldBePresent() {
    List<UserGroup> results = queryFactory.selectFrom(QUserGroup.userGroup).fetch();
    Assertions.assertEquals(3, results.size());
}

Using the selectFrom() method of the JPAQueryFactory starts building a query for our entity. Then, fetch() retrieves the values from the database into the persistence context. Finally, we’ve achieved the same result, but our query-building process is significantly shorter.

4. Filtering, Ordering and Grouping

Let’s delve into a more complex example. We’ll explore how our frameworks handle filtering, sorting, and data aggregation queries.

4.1. JPA Criteria

In this example, we’ll query all the UserGroup entities filtering them using names, which should be in one of two lists. The result we’ll sort by UserGroup name in descending order. Additionally, we’ll aggregate unique IDs per each UserGroup from the result:

@Test
void givenJpaCriteria_whenGetTheUserGroups_thenExpectedAggregatedDataShouldBePresent() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Object[]> cr = cb.createQuery(Object[].class);
    Root<UserGroup> root = cr.from(UserGroup.class);

    CriteriaQuery<Object[]> select = cr
      .multiselect(root.get(UserGroup_.name), cb.countDistinct(root.get(UserGroup_.id)))
      .where(cb.or(
        root.get(UserGroup_.name).in("Group 1", "Group 2"),
        root.get(UserGroup_.name).in("Group 4", "Group 5")
      ))
      .orderBy(cb.desc(root.get(UserGroup_.name)))
      .groupBy(root.get(UserGroup_.name));

    TypedQuery<Object[]> query = em.createQuery(select);
    List<Object[]> results = query.getResultList();
    assertEquals(2, results.size());
    assertEquals("Group 2", results.get(0)[0]);
    assertEquals(1L, results.get(0)[1]);
    assertEquals("Group 1", results.get(1)[0]);
    assertEquals(1L, results.get(1)[1]);
}

All the base methods here are the same as in the previous JPA Criteria section. Instead of selectFrom(), in this example, we use multiselect(), where we specify all the items that will be returned. We use the second parameter of this method for the aggregated amount of UserGroup IDs. In the where() method, we added filters we’ll apply to our query.

Then we call the orderBy() method, specifying the ordering field and type. Finally, in the groupBy() method, we specify a field that will be our key for aggregated data.

As we can see, a few UserGroup items were returned. They’re placed in the expected order and the result also contains aggregated data.

4.2. Querydsl

Now, let’s make the same query using Querydsl:

@Test
void givenQueryDSL_whenGetTheUserGroups_thenExpectedAggregatedDataShouldBePresent() {
    List<Tuple> results = queryFactory
      .select(userGroup.name, userGroup.id.countDistinct())
      .from(userGroup)
      .where(userGroup.name.in("Group 1", "Group 2")
        .or(userGroup.name.in("Group 4", "Group 5")))
      .orderBy(userGroup.name.desc())
      .groupBy(userGroup.name)
      .fetch();

    assertEquals(2, results.size());
    assertEquals("Group 2", results.get(0).get(userGroup.name));
    assertEquals(1L, results.get(0).get(userGroup.id.countDistinct()));
    assertEquals("Group 1", results.get(1).get(userGroup.name));
    assertEquals(1L, results.get(1).get(userGroup.id.countDistinct()));
}

Aiming for grouping functionality, we’ve replaced the selectFrom() method with two separate methods. In the select() method, we’ve specified the group field and aggregated function. In the from() method, we instruct the query builder on which entity should be applied. Similar to JPA Criteria, where(), orderBy(), and groupBy() are used to describe the filtering, ordering, and fields for grouping.

Finally, we achieved the same result with a slightly more compact syntax.

5. Complex Queries With JOINs

In this example, we’ll create complex queries that join all our entities. The result will contain a list of UserGroup entities with all their related entities.

Let’s prepare some data for our tests:

Stream.of("Group 1", "Group 2", "Group 3")
  .forEach(g -> {
      UserGroup userGroup = new UserGroup();
      userGroup.setName(g);
      em.persist(userGroup);
      IntStream.range(0, 10)
        .forEach(u -> {
            GroupUser groupUser = new GroupUser();
            groupUser.setLogin("User" + u);
            groupUser.getUserGroups().add(userGroup);
            em.persist(groupUser);
            userGroup.getGroupUsers().add(groupUser);
            IntStream.range(0, 10000)
              .forEach(t -> {
                  Task task = new Task();
                  task.setDescription(groupUser.getLogin() + " task #" + t);
                  task.setUser(groupUser);
                  em.persist(task);
              });
        });
      em.merge(userGroup);
  });

So, in our database, we’ll have three UserGroups, each containing ten GroupUsers. Each GroupUser will have ten thousand Tasks.

5.1. JPA Criteria

Now, let’s make a query using JPA CriteriaBuider:

@Test
void givenJpaCriteria_whenGetTheUserGroupsWithJoins_thenExpectedDataShouldBePresent() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<UserGroup> query = cb.createQuery(UserGroup.class);

    query.from(UserGroup.class)
      .<UserGroup, GroupUser>join(GROUP_USERS, JoinType.LEFT)
      .join(tasks, JoinType.LEFT);

    List<UserGroup> result = em.createQuery(query).getResultList();
    assertUserGroups(result);
}

We use the join() method specifying the entity we want to join with and its type. After the execution, we retrieved a list of results. Let’s assert it using the following code:

private void assertUserGroups(List<UserGroup> userGroups) {
    assertEquals(3, userGroups.size());
    for (UserGroup group : userGroups) {
        assertEquals(10, group.getGroupUsers().size());
        for (GroupUser user : group.getGroupUsers()) {
            assertEquals(10000, user.getTasks().size());
        }
    }
}

As we can see, all the expected items were retrieved from the database.

5.2. Querydsl

Let’s achieve the same goal using Querydsl:

@Test
void givenQueryDSL_whenGetTheUserGroupsWithJoins_thenExpectedDataShouldBePresent() {
    List<UserGroup> result = queryFactory
      .selectFrom(userGroup)
      .leftJoin(userGroup.groupUsers, groupUser)
      .leftJoin(groupUser.tasks, task)
      .fetch();

    assertUserGroups(result);
}

Here, we use the leftJoin() method to add the connection to another entity. All the join types have separate methods. Both syntaxes are not very wordy. In the Querydsl implementation, our query is slightly more readable.

6. Modifying Data

Both frameworks support data modification. We can utilize it to update data based on complex and dynamic criteria. Let’s see how it works.

6.1. JPA Criteria

Let’s update UserGroup with a new name:

@Test
void givenJpaCriteria_whenModifyTheUserGroup_thenNameShouldBeUpdated() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaUpdate<UserGroup> criteriaUpdate = cb.createCriteriaUpdate(UserGroup.class);
    Root<UserGroup> root = criteriaUpdate.from(UserGroup.class);
    criteriaUpdate.set(UserGroup_.name, "Group 1 Updated using Jpa Criteria");
    criteriaUpdate.where(cb.equal(root.get(UserGroup_.name), "Group 1"));

    em.createQuery(criteriaUpdate).executeUpdate();
    UserGroup foundGroup = em.find(UserGroup.class, 1L);
    assertEquals("Group 1 Updated using Jpa Criteria", foundGroup.getName());
}

To modify the data we use a CriteriaUpdate instance, which is used to create a Query. We set all the field names and values are going to be updated. Finally, we call the executeUpdate() method to run the update query. As we can see, we have a modified name field in the updated entity.

6.2. Querydsl

Now, let’s update UserGroup using Querydsl:

@Test
void givenQueryDSL_whenModifyTheUserGroup_thenNameShouldBeUpdated() {
    queryFactory.update(userGroup)
      .set(userGroup.name, "Group 1 Updated Using QueryDSL")
      .where(userGroup.name.eq("Group 1"))
      .execute();

    UserGroup foundGroup = em.find(UserGroup.class, 1L);
    assertEquals("Group 1 Updated Using QueryDSL", foundGroup.getName());
}

From queryFactory we create the update query by calling the update() method. Then, we set new values for the entity fields using the set() method. We’ve updated the name successfully. Similar to previous examples, Querydsl offers a slightly shorter and more declarative syntax.

7. Integration With Spring Data JPA

We can use Querydsl and JPA Criteria to implement dynamic filtering in our Spring Data JPA repositories. Let’s add Spring Data JPA starter dependency first:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <version>3.2.3</version>
</dependency>

7.1. JPA Criteria

Let’s create a Spring Data JPA repository for our UserGroup extending JpaSpecificationExecutor:

public interface UserGroupJpaSpecificationRepository 
  extends JpaRepository<UserGroup, Long>, JpaSpecificationExecutor<UserGroup> {

    default List<UserGroup> findAllWithNameInAnyList(List<String> names1, List<String> names2) {
        return findAll(specNameInAnyList(names1, names2));
    }

    default Specification<UserGroup> specNameInAnyList(List<String> names1, List<String> names2) {
        return (root, q, cb) -> cb.or(
          root.get(UserGroup_.name).in(names1),
          root.get(UserGroup_.name).in(names2)
        );
    }
}

In this repository, we’ve created a method that filters our results based on any of two name lists from the parameters. Let’s use it and see, how it works:

@Test
void givenJpaSpecificationRepository_whenGetTheUserGroups_thenExpectedDataShouldBePresent() {
    List<UserGroup> results = userGroupJpaSpecificationRepository.findAllWithNameInAnyList(
      List.of("Group 1", "Group 2"), List.of("Group 4", "Group 5"));

    assertEquals(2, results.size());
    assertEquals("Group 1", results.get(0).getName());
    assertEquals("Group 4", results.get(1).getName());
}

We can see that the result list contains exactly the expected groups.

7.2. Querydsl

The same functionality we can achieve using Querydsl Predicate. Let’s create another Spring Data JPA repository for the same entity:

public interface UserGroupQuerydslPredicateRepository 
  extends JpaRepository<UserGroup, Long>, QuerydslPredicateExecutor<UserGroup> {

    default List<UserGroup> findAllWithNameInAnyList(List<String> names1, List<String> names2) {
        return StreamSupport
          .stream(findAll(predicateInAnyList(names1, names2)).spliterator(), false)
          .collect(Collectors.toList());
    }

    default Predicate predicateInAnyList(List<String> names1, List<String> names2) {
        return new BooleanBuilder().and(QUserGroup.userGroup.name.in(names1))
          .or(QUserGroup.userGroup.name.in(names2));
    }
}

QuerydslPredicateExecutor provides only Iterable as the container for multiple results. If we want to use another type, we must handle the conversions ourselves. As we can see, the client code for this repository will be very similar to that for JPA specifications:

@Test
void givenQuerydslPredicateRepository_whenGetTheUserGroups_thenExpectedDataShouldBePresent() {
    List<UserGroup> results = userQuerydslPredicateRepository.findAllWithNameInAnyList(
      List.of("Group 1", "Group 2"), List.of("Group 4", "Group 5"));

    assertEquals(2, results.size());
    assertEquals("Group 1", results.get(0).getName());
    assertEquals("Group 4", results.get(1).getName());
}

8. Performance

Querydsl ultimately prepares the same criteria query but introduces additional conventions beforehand. Let’s measure how this process impacts the performance of our queries. To measure execution time, we can use our IDE functionality or create a timing extension.

We’ve executed all our test methods a few times and saved the median result into a list:

Method [givenJpaSpecificationRepository_whenGetTheUserGroups_thenExpectedDataShouldBePresent] took 128 ms.
Method [givenQuerydslPredicateRepository_whenGetTheUserGroups_thenExpectedDataShouldBePresent] took 27 ms.
Method [givenJpaCriteria_whenGetAllTheUserGroups_thenExpectedNumberOfItemsShouldBePresent] took 1 ms.
Method [givenQueryDSL_whenGetAllTheUserGroups_thenExpectedNumberOfItemsShouldBePresent] took 3 ms.
Method [givenJpaCriteria_whenModifyTheUserGroup_thenNameShouldBeUpdated] took 13 ms.
Method [givenQueryDSL_whenModifyTheUserGroup_thenNameShouldBeUpdated] took 161 ms.
Method [givenJpaCriteria_whenGetTheUserGroupsWithJoins_thenExpectedDataShouldBePresent] took 887 ms.
Method [givenQueryDSL_whenGetTheUserGroupsWithJoins_thenExpectedDataShouldBePresent] took 728 ms.
Method [givenJpaCriteria_whenGetTheUserGroups_thenExpectedAggregatedDataShouldBePresent] took 5 ms.
Method [givenQueryDSL_whenGetTheUserGroups_thenExpectedAggregatedDataShouldBePresent] took 88 ms.

As we can see, in most cases, we achieve similar execution times for both Querydsl and JPA Criteria. In the modification case, Querydsl uses JPQLSerializer and prepares a JPQL query string, which leads to additional overhead.

9. Conclusion

In this article, we’ve thoroughly compared JPA Criteria and Querydsl in various scenarios. In many cases, Querydsl emerged as the preferable option due to its slightly more user-friendly syntax. If a few more dependencies in the project are not an issue, we can consider it a good tool to improve our code readability. On the other hand, we can achieve all the functionality using JPA criteria.

As usual, the full source code can be found over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.