Persistence top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we'll discuss the different types of JPA queries. Moreover, we'll focus on comparing the differences between them and expanding on each one's pros and cons.

2. Setup

Firstly, let's define the UserEntity class we'll use for all examples in this article:

@Table(name = "users")
@Entity
public class UserEntity {

    @Id
    private Long id;
    private String name;
    //Standard constructor, getters and setters.

}

There are three basic types of JPA Queries:

  • Query, written in Java Persistence Query Language (JPQL) syntax
  • NativeQuery, written in plain SQL syntax
  • Criteria API Query, constructed programmatically via different methods

Let's explore them.

3. Query

A Query is similar in syntax to SQL, and it's generally used to perform CRUD operations:

public UserEntity getUserByIdWithPlainQuery(Long id) {
    Query jpqlQuery = getEntityManager().createQuery("SELECT u FROM UserEntity u WHERE u.id=:id");
    jpqlQuery.setParameter("id", id);
    return (UserEntity) jpqlQuery.getSingleResult();
}

This Query retrieves the matching record from the users table and also maps it to the UserEntity object.

There are two additional Query sub-types:

  • TypedQuery
  • NamedQuery

Let's see them in action.

3.1. TypedQuery

We need to pay attention to the return statement in our previous example. JPA can't deduce what the Query result type will be, and, as a result, we have to cast.

But, JPA provides a special Query sub-type known as a TypedQuery. This is always preferred if we know our Query result type beforehand. Additionally, it makes our code much more reliable and easier to test.

Let's see a TypedQuery alternative, compared to our first example:

public UserEntity getUserByIdWithTypedQuery(Long id) {
    TypedQuery<UserEntity> typedQuery
      = getEntityManager().createQuery("SELECT u FROM UserEntity u WHERE u.id=:id", UserEntity.class);
    typedQuery.setParameter("id", id);
    return typedQuery.getSingleResult();
}

This way, we get stronger typing for free, avoiding possible casting exceptions down the road.

3.2. NamedQuery

While we can dynamically define a Query on specific methods, they can eventually grow into a hard to maintain code base. What if we could keep general usage queries in one centralized, easy to read place?

JPA's also got us covered on this with another Query sub-type known as a NamedQuery.

We define NamedQuery on the Entity class itself, providing a centralized, quick and easy way to read and find Entity‘s related queries.

All NamedQueries must have a unique name.

Let's see how we can add a NamedQuery to our UserEntity class:

@Table(name = "users")
@Entity
@NamedQuery(name = "UserEntity.findByUserId", query = "SELECT u FROM UserEntity u WHERE u.id=:userId")
public class UserEntity {

    @Id
    private Long id;
    private String name;
    //Standard constructor, getters and setters.

}

The @NamedQuery annotation has to be grouped inside a @NamedQueries annotation if we're using Java before version 8. From Java 8 forward, we can simply repeat the @NamedQuery annotation at our Entity class.

Using a NamedQuery is very simple:

public UserEntity getUserByIdWithNamedQuery(Long id) {
    Query namedQuery = getEntityManager().createNamedQuery("UserEntity.findByUserId");
    namedQuery.setParameter("userId", id);
    return (UserEntity) namedQuery.getSingleResult();
}

4. NativeQuery

A NativeQuery is simply an SQL query. These allow us to unleash the full power of our database, as we can use proprietary features not available in JPQL-restricted syntax.

This comes at a cost. We lose database portability of our application with NativeQuery because our JPA provider can't abstract specific details from the database implementation or vendor anymore.

Let's see how to use a NativeQuery that yields the same results as our previous examples:

public UserEntity getUserByIdWithNativeQuery(Long id) {
    Query nativeQuery
      = getEntityManager().createNativeQuery("SELECT * FROM users WHERE id=:userId", UserEntity.class);
    nativeQuery.setParameter("userId", id);
    return (UserEntity) nativeQuery.getSingleResult();
}

We must always consider if a NativeQuery is the only option. Most of the time, a good JPQL Query can fulfill our needs and most importantly, maintain a level of abstraction from the actual database implementation.

Using NativeQuery doesn't necessarily mean locking ourselves to one specific database vendor. After all, if our queries don't use proprietary SQL commands and are using only a standard SQL syntax, switching providers should not be an issue.

5. Criteria API Query

Criteria API queries are programmatically-built, type-safe queries – somewhat similar to JPQL queries in syntax:

public UserEntity getUserByIdWithCriteriaQuery(Long id) {
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<UserEntity> criteriaQuery = criteriaBuilder.createQuery(UserEntity.class);
    Root<UserEntity> userRoot = criteriaQuery.from(UserEntity.class);
    UserEntity queryResult = getEntityManager().createQuery(criteriaQuery.select(userRoot)
      .where(criteriaBuilder.equal(userRoot.get("id"), id)))
      .getSingleResult();
    return queryResult;
}

It can be daunting to use Criteria API queries first-hand, but they can be a great choice when we need to add dynamic query elements or when coupled with the JPA Metamodel.

6. Conclusion

In this quick article, we learned what JPA Queries are, along with their usage.

JPA Queries are a great way to abstract our business logic from our data access layer as we can rely on JPQL syntax and let our JPA provider of choice handle the Query translation.

All code presented in this article is available over on GitHub.

Persistence bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
newest oldest most voted
Notify of
pcdavid
Guest
pcdavid

In section 4 on NativeQuery, shouldn’t line 4 be nativeQuery.setParameter(“userId”, id) instead of nativeQuery.setParameter(“id”, id) ?

Loredana Crusoveanu
Editor

Yep, thanks for the note. Fixed.

Comments are closed on this article!