HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Shortening JPA criteria query boilerplate

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
criteriashorteningqueryboilerplatejpa

Problem

I've used hibernate for a long time. Recently I started using JPA, but I can't find a short way to write a simple select in less than these seven lines (the use of criteria is a must in this project).

Is there a shorter way to build this query?

public List findDevolucionesByOriginalOperationId(String originalOperationId) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(Transaction.class);
    Root root = cq.from(Transaction.class);
    Collection  predicates = new ArrayList();

    predicates.add(cb.equal(root.get("originalOperationId"), originalOperationId));

    cq.where(predicates.toArray(new Predicate[predicates.size()]));
    List resultado = em.createQuery(cq).getResultList();
    return resultado;
}

Solution

JPA Criteria API is horrific, even the creators admitted that it was designed for tooling support rather than for developers.
My personal favorite approach is to use a fluent query API like QueryDSL.

The query in QueryDSL would look more or less as follows:

new JPAQuery().from(transaction)
    .where(transaction.originalOperationId.eq(originalOperationId))
   .list();


The difference is staggering. And the query is fully typesafe.

Code Snippets

new JPAQuery().from(transaction)
    .where(transaction.originalOperationId.eq(originalOperationId))
   .list();

Context

StackExchange Code Review Q#79776, answer score: 4

Revisions (0)

No revisions yet.