Java Reference
In-Depth Information
•
Criteria API
: These queries can be formed by simply executing Java methods
and the usage of appropriate objects. Since JPA 2.1, it's possible to perform bulk
updates and deletions through this API.
Let's make a simple comparison of these three methods using an example. We want to just
get all the objects of a given type. Using native SQL, this query would look like this:
entityManager.createNativeQuery("SELECT * from
seat_type").getResultList()
As you can see, it uses standard SQL in the form of a string. Now let's look at JPQL:
entityManager.createQuery("select seatType from SeatType
seatType").getResultList();
It's easy to notice its similarity to SQL but a bit different. It uses, for example, class name
instead of table name. However, again, it's a query in a string. The last example is the Cri-
teria API:
final CriteriaQuery<SeatType> criteriaQuery =
em.getCriteriaBuilder().createQuery(SeatType.class);
criteriaQuery.select(criteriaQuery.from(SeatType.class));
em.createQuery(criteriaQuery).getResultList();
At first glance, it looks like the most complicated one, but it has some advantage, that is, it
does not use any strings (which are usually error-prone and hard to refactor). Both JPQL
and Criteria API have many improvements in the newest JPA version, concerning join op-
erations using the
on
condition, database functions support, and arithmetic subqueries.
You may ask yourself, "Which one should I use?" It's a hard question because all of them
have their pros and cons so it depends on the specific case. Basically, Criteria query and
named queries are normally a safe bet. Native SQL should have a really good justifica-
tion, as it's usually not portable between different vendors and cannot be validated by JPA
before the execution.