Question

I understand the advantages of using a JPA criteria builder above the Java Persistence Query Language.

Is there an easy way to explain how to build up this kind of queries? I need a more human readable explanation to build up my queries, this to have a kind of intuitive approach to query my database.

Example:

SQL:

SELECT id,status,created_at from transactions where status='1' 
and currency='USD' and appId='123' order by id

Critera Builder with MetaModel:

Map<SingularAttribute<Transaction, ?>, Object> params = ...;
CriteriaBuilder cb = em.getCriteriaBuilder();           
CriteriaQuery<Tuple> cq = cb.createTupleQuery();     
Root<Transaction> r = cq.from(Transaction.class);

Predicate p= cb.conjunction();
for (Map.Entry<SingularAttribute<Transaction, ?>, Object> param: params.entrySet())
    p = cb.and(p, cb.equal(r.get(param.getKey()), param.getValue()));

cq.multiselect(r.get(Transaction_.id), r.get(Transaction_.status), 
          r.get(Transaction_.created_at))
    .where(p)
    .orderBy(cb.asc(r.get(Transaction_.id)));

List<Tuple> result = em.createQuery(cq).getResultList();

This example was based on another question: Complex queries with JPA criteria builder

Was it helpful?

Solution

I don't think there's an more clean way to write that kind of query following the standards and not using an hand wrote JPQL query, anyway out of the standard the are many query builders like: query dsl or Torpedo query or Object Query that allow to write query in a more clean way if that can help :)

OTHER TIPS

Criteria query have some advantages of JPQL, such as: type safety, write SQL querias based on Java Programming model and make it portable. The easiest way in which I understand this when I started to work with JPA is think in the main objects that you need to use and their features.

CriteriaBuilder: Any statement that can be done using SQL like functions, reserved works, operations, predicates are part of this class, so builder need to be used to create those and apply them to the criteriaQuery.

CriteriaQuery: Any statement to have as goal to create a formal SQL statement are here, think on this as the boilerplate of the query definition, it have from, select, where, group by and all the statements, so this is the query itself and must be use to determine what you are really looking for from the database.

Now think to do a query you always must to use a Root, this mean select what will be your main table in your query definitions, based on that and helping from CriteriaQuery and CriteriaBuilder objects you can redefine the search to be whatever you want.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top