DBA > Articles

Writing type-safe JPA queries with QueryDSL

By:
To read more DBA articles, visit http://dba.fyicenter.com/article/

I became a fan of type-safe queries long time ago (unless I need plain SQL queries via JDBC). What are type-safe queries and how easily they can be maintained? Criteria, QueryDSL, JOOQ? This post is not about which framework is the best one. It’s about how easily implement JPA queries using QueryDSL.

I believe JOOQ is a great framework for plain SQL based environments, however my main work is based on JPA environments, so I chose QueryDSL. Why not the standard - Criteria? Due to it’s complexity. I always try to make things simple, and using Criteria is not the case.

JPQL is great to develop things fast, but maintenance is slow when you change your entity structure. And you do not see the issues unless you know the code by heart. But what if that code is not written by you? Unit tests - true, but sometimes the life is not so easy as we would like it to be :) In that case QueryDSL gives you some advantage to trace the appearing query issues easily during compile time. It does not solve all your issues, but at least it minimizes them :)

Concerns: Tim has left Mysema, however I believe he will continue to support QueryDSL project!
Preconditions
You need this environment setup in order to successfully complete the provided guide:
Apache Maven 3.x
Eclipse Luna
QueryDSL
JPA model

Issue
The main issue here is the complexity of Criteria API in order to create a JPA type-safe query. I am able to write a fast query using JPQL, but it also might be a buggy one as well. On other hand I am free to to build a type-safe query with Criteria API, but for that reason I need a CriteriaBuilder, Root and CriteriaQuery. Let’s take an example:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(BlogEntry.class);
Root be = cq.from(BlogEntry.class);
cq.select(be);
TypedQuery q = em.createQuery(cq);
List allItems = q.getResultList();

Assert.assertTrue(allItems.isEmpty());
Too many things to do and remember.
Solution
With QueryDSL your things to remember are minimised and you may start doing what you were intended to do - write a query. Of course, you need to setup your environment to create a metamodel for you:

Full article...


Other Related Articles

... to read more DBA articles, visit http://dba.fyicenter.com/article/