Pos Graduation : MIT Software Engineering – Java (Infnet College) Developer Experience: 10+ years on systems developments 7+ years as Delphi developer 3+ years as Java developer 8+ months as Java teacher Agile, Scrum, TDD SQLServer, Oracle, Postgres, MySQL Java Certifications: SCJP (1.6) SCWCD (1.5) OCBCD In Progress Hebert is a DZone MVB and is not an employee of DZone and has posted 6 posts at DZone. You can read more from them at their website. View Full User Profile

Easy Criteria – JPA Criteria's Saving Grace

07.25.2012
| 5209 views |
  • submit to reddit
Hello, 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&amp;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_
Published at DZone with permission of Hebert Coelho De Oliveira, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Nicolas Frankel replied on Wed, 2012/07/25 - 1:39pm

Would you use Hibernate, you could use Query By Example. It let you go of the "if" and is native (no need to get a library - save Hibernate).

Go have a look: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-examples

Wal Rus replied on Wed, 2012/07/25 - 4:08pm

>If you always wanted to use the JPA Criteria but thought it was too verbose and complex, a solution has arrived—Easy Criteria. 

 

Hm... That JPA was supposed to be EASY, RrrrRemember??? 

Hebert Coelho D... replied on Wed, 2012/07/25 - 4:24pm in response to: Nicolas Frankel

Hello Nicolas,

 The idea of this framework is to avoid to be coupled to a JPA Implementation. You can use the EasyCriteria with EclipseLink, OpenJPA without the Hibernate library. The EasyCriteria framework makes your application JPA Implementation portable.

It is easier to inject a EntityManager than a Hibernate Session.

[=

Hebert Coelho D... replied on Wed, 2012/07/25 - 4:25pm in response to: Wal Rus

I do think it is EASY.

I think that only the JPA Criteria is the "black sheep" (brazilian expression to express something like "the weakness or the wrong result")!

Nathanaël Roberts replied on Thu, 2012/07/26 - 1:57am

Did you try QueryDSL ? It's just impressive how concise, readable and easy to use it is.

In your article you should have used the JPA metamodels too because it makes the queries typesafe. Is EasyCriteria compatible with JPA metamodels (or another metamodel) ?

Slim Ouertani replied on Thu, 2012/07/26 - 8:23am

Criteria are fro hibernate ORM before to be standard or Oracle developers idea

Hebert Coelho D... replied on Thu, 2012/07/26 - 12:18pm in response to: Nathanaël Roberts

Hello Nathanaël,

 The idea of EasyCriteria is to make easier to run the queries. The user will not need to create any kind of metamodels. The developer will not need to create any additional class to run the EasyCriteria. 

 The created query will result in a TypedQuery so the query will not have a type cast problem.

 As future improvements EasyCriteria will support  MetaModel. [=

Hebert Coelho D... replied on Thu, 2012/07/26 - 12:19pm in response to: Slim Ouertani

Indeed!

 If Oracle used the same pattern of Hibernate that verbosity problem  would not exist. [=

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.