Easy Criteria – JPA Criteria's Saving Grace
Join the DZone community and get the full member experience.
Join For FreeHello, how are you?
Today we will see about this tool that makes it easier to use the JPA Criteria. The application that uses this library will be cleaner, easier to use, and portable across the JPA implementations.
At the end of this post you will find the source code to download.
What is Criteria? Currently, many think it is the best solution to create dynamic queries. Imagine a page that allows the user to do several types of queries; the requested query could be by name, by age, or with both. Take a look below to see how the query would appear if we concatenate a String:
EntityManager em = emf.createEntityManager(); String hql = "select p from Person p where 1=1 "; if(parameters[0].equals("name")){ hql += " and p.name = '" + values[0] + "'"; } if(parameters[1].equals("age")){ hql += " and p.age = " + values[1]; } TypedQuery<Person> query = em.createQuery(hql, Person.class); System.out.println(query.getResultList());
Notice that a String concatenation is made in the code above; remember that this practice is a bad and dangerous practice because it allows “SQL Injection” hacker attacks. To avoid these attacks we should use a query with parameters:
EntityManager em = emf.createEntityManager(); String hql = "select p from Person p where 1=1 "; if(parameters.contains("name")){ hql += " and p.name = :name"; } if(parameters.contains("age")){ hql += " and p.age = :age"; } TypedQuery<Person> query = em.createQuery(hql, Person.class); if(parameters.contains("name")){ query.setParameter("name", values[0].toString()); } if(parameters.contains("age")){ query.setParameter("age", Integer.valueOf(values[1].toString())); }
System.out.println(query.getResultList());
Notice that though the SQL Injection problem is solved, the code must now check parameters to add it to the query and later to pass its values. The code needs two “parameters searches” to complete the task.
Perfect to this kind of situation is the idea Java/Oracle developers had when they created the Criteria. Below, you can see how the code would look with the native JPA Criteria:
EntityManager em = emf.createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Person> cq = cb.createQuery(Person.class); Root<Person> root = cq.from(Person.class); cq.select(root); if(parameters.contains("name")){ Path<String> name = root.get("name"); cq.where(cb.and(cb.equal(name, values[0]))); } if(parameters.contains("age")){ Path<Integer> name = root.get("age"); cq.where(cb.and(cb.equal(name, Integer.valueOf(values[1].toString())))); } TypedQuery<Person> query = em.createQuery(cq); System.out.println(query.getResultList())
Now, passing the parameters values is easier. There is no need to concatenate the String or to check the parameters list values to populate the values.
Unfortunately the Criteria API is too complex and verbose to the extreme. If you want to do only a “select p from Person p,” you would need to create the criteria bellow:
EntityManager em = emf.createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Person> cq = cb.createQuery(Person.class); Root<Person> root = cq.from(Person.class); cq.select(root); TypedQuery<Person> query = em.createQuery(cq); System.out.println(query.getResultList());</pre> EntityManager em = emf.createEntityManager();
This is too much code to do something so easy, to list all persons from a table.
To avoid all this verbosity, the Open Source project named EasyCriteria was created. If a developer uses the EasyCriteria the query above would look like that shown below:
EntityManager em = emf.createEntityManager(); EasyCriteria<Person> easyCriteria = EasyCriteriaFactory.createQueryCriteria(em, Person.class); if(parameters.contains("name")){ easyCriteria.whereEquals("name", values[0]); } if(parameters.contains("age")){ easyCriteria.whereEquals("age", values[1]); }
System.out.println(easyCriteria.getResultList());
Notice that all that JPA verbosity is gone. Now it is possible to have clean code, and it's easier to create dynamic queries. The code above is still worth talking about:
- Line 2: An instance of the EasyCriteria is created through a “factory.” This factory exists to do the abstraction of every needed step to create an object of the EasyCriteriaImp type. In future versions, new types of the EasyCriteria will be added, e.g. “Tuple.”
- Lines 5 and 9: It is easier to pass the parameters. To pass the parameters to compare values (“name = :name”) just use the equals method that makes the first parameter the attribute name; the second parameter will be the value that will be equaled.
- Line 12: To run the query it will not be necessary to use the Query interface. The EasyCriteria itself takes this responsibility. It is possible to extract the query result through the EasyCriteria. Here are two available methods to get the query result: EasyCriteria.getSingleResult(), EasyCriteria.getResultList().
In the EasyCriteria web page, several code samples are available and the methods that can be used. Another advantage of the EasyCriteria is the ability to “link” all methods:
easyCriteria.whereEquals("name", values[0]).whereEquals("age", values[1]).getResultList();
easyCriteria.whereEquals("name", values[0]).whereEquals("age", values[1]).getResultList();
It is a light-weight library because the only dependency the stystem will need to have is the JPA. Attention: your application will need to have a JPA implementation up and running.
This library was developed with JUnit and tested with Hibernate, OpenJPA and EclipseLink. The JUnit also uses the Cobertura framework (http://uaihebert.com/?p=63) to check if all code lines (or most of them) are covered by the tests (so far we got 100% coverage).

EasyCriteria still in Beta but the development team already planned some releases and functionalities.
Other EasyCriteria advantages: Your software code is no long “coupled” to any kind of JPA implementation. Today the Hibernate has a good criteria tool, but your code must stay “attached” to it. With the EasyCriteria you will be able to use any kind of JPA implementation. The proof of this decoupled library is that the EasyCriteria has been tested with the 3 implementations quoted earlier.
The EasyCriteria has the methods "in," "like," "empty" and others. The developer will be able to do join (just simple joins without parameter), distinct or even order by all with such Criteria.
Here you will find the EasyCriteria (http://easycriteria.uaihebert.com) to download and have access to all of its documentation.
Click here to download the source code of this post (https://sites.google.com/site/uaihebertdeposito/EasyCriteriaPost.zip?attredirects=0&d=1).
I hope that this post/tool may help you.
If you have any doubt/question/comment just post it in the comments area.
See you soon! \o_
Database
code style
Grace (plotting tool)
Published at DZone with permission of Hebert Coelho De Oliveira, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Boosting Application Performance With MicroStream and Redis Integration
-
Working on an Unfamiliar Codebase
-
Security Challenges for Microservice Applications in Multi-Cloud Environments
-
Building and Deploying Microservices With Spring Boot and Docker
Comments