EasyCriteria 2.0 – JPA Criteria should be easy

16

Posted on February 14, 2013 by

Share it now!

Hello, how are you?

It has been a long time since my last post, but I was not doing nothing during this time.

In the post today we will see about the new version of the framework named EasyCriteria. At the end of this post we will see what is to come here in the blog.

Unfortunately the JPA criteria has a huge problem that is its verbosity. Why not make easier? Thinking like this that EasyCriteria framework were born and now it is on version 2.0.

To do a simple JPQL with the JPA Criteria the following code would be needed:

CriteriaQuery<Person> criteriaQuery = criteriaBuilder.createQuery(Person.class);
Root<Person> root = criteriaQuery.from(Person.class);
criteriaQuery.select(root);
TypedQuery<Person> query = entityManager.createQuery(criteriaQuery);
query.getResultList();

Notice all the code needed to do the query: select p from Person p.

Check below how easy it is to do the same Criteria with EasyCriteria:

EasyCriteria<Person> easyCriteria = EasyCriteriaFactory.createQuery(entityManager, Person.class);
easyCriteria.getResultList();

The difference between version 1.0 and the 2.0 version is in the reduction of methods into generic methods. To compare methods with =, >=, <, <=, and other methods just use the API like below:

easyCriteria.andGreaterThan("hairSize", 10.4f); // >

easyCriteria.andGreaterOrEqualTo("height", 11.00d); // >=

easyCriteria.andLessThan("totalBooksOwned", 30L); // <

easyCriteria.andLessOrEqualTo("firstJobDate", firstJobDate); // <=

easyCriteria.andJoinEquals("dogs", "age", 15); // =

easyCriteria.andJoinStringIn("dogs", "name", names); // value in (x, i, z, ...)

easyCriteria.andJoinStringLike("dogs", "name", "%y");

One of the ideals of the EasyCriteria framework is to expose the lower number possible of API to the user. Thinking like this, EasyCriteria added the “OR” condition to its API without new classes.

Take a look below to see how to do queries with OR:

select s from Song s where s.id = 1 or s.length = 40 or s.artist = 'Group 1 Crew'
easyCriteria.orEquals("id", 1).orEquals("length", 40).orEquals("artist", "Group 1 Crew");

Another type of OR could be done:

select s from Song s where (s.id = 1) or (s.id = 2) or (s.length = 40) or (s.artist = 'Group 1 Crew')
easyCriteria.orEquals("id", 1, 2).orEquals("length", 40).orEquals("artist", "Group 1 Crew");

And it is possible to do complexes queries cases like:

select s from Song s where (s.totalDownloads = 20 or s.weight = 10.00) and (s.price = 20.00 or s.type = :type)
easyCriteria.orEquals(1, "totalDownloads", 20L).orEquals(1, "weight", 10.00f).orEquals(2, "price", 20.00d).orEquals(2, "type", SongType.PRAISE);

The idea of index were added to the API to be used with a group of OR. The first OR group is composed of “totalDownloads” and “weight”, the second group has “price” and “type” as elements.

As default index the value 1 is always used. The criteria above could be written as:

easyCriteria.orEquals("totalDownloads", 20L).orEquals("weight", 10.00f).orEquals(2, "price", 20.00d).orEquals(2, "type", SongType.PRAISE);

It is possible create a query to do the inverse of the query above, AND separated by OR:

select s from Song s where (s.id = 1 and s.name = 'Sing Out') or (s.id = 2 and s.name = 'Alive')
easyCriteria.addAndSeparatedByOr(1, "id", 1).addAndSeparatedByOr(1, "name", "Sing Out").addAndSeparatedByOr(2, "id", 2).addAndSeparatedByOr(2, "name", "Alive");

That is all for today, I hope you like the new version. It will take a long time to consider this framework complete. Helping with the OR functionality I could count with João Neves (http://about.me/joaonevesfilho) and Sasaki (http://curriculum.rodrigosasaki.com/).

Here it is possible to see the framework official page: http://easycriteria.uaihebert.com/. And the best, it is open source (http://code.google.com/p/easy-criteria/).

Other fact about the framework is that it is 100% covered with tests using Cobertura. EasyCriteria was tested with OpenJPA, EclipseLink and Hibernate. Now it is time to ask for your help. It was found bugs in the tested implementations; it would be wonderful if you spare 5 minutes of your time voting in the bugs. With your vote the bug could be corrected faster.

EclipseLink: https://bugs.eclipse.org/bugs/show_bug.cgi?id=386354
OpenJPA: https://issues.apache.org/jira/browse/OPENJPA-2333
Hibernate: https://hibernate.onjira.com/browse/HHH-7985

What is to come in the blog? It took so much time for me to write this post because I am finishing my first book. If God’s will, the book will be released in March.

In this pause of new posts here, I have studied a lot of Maven and I want my next post to be about a mini book about a basic Maven and full web applications. Yes, I said “applications” in plural. [=

See you soon. \o_

Response to EasyCriteria 2.0 – JPA Criteria should be easy

  1. Michael Encarnacion

    Thank you for this. This is very helpful.
    There is this one problem I am facing though.
    How do i add a criteria, say an equal case, to an embedded id?

    I have the following classes.
    @Entity
    public MyClass implements Serializable {

    @EmbeddedId
    private MyClassPK id;
    ….
    }
    @Embeddable
    public MyClassPK implements Serializable {

    @Column(unique=true, nullable=false, length=50)
    private String id;
    @Column(unique=true, nullable=false, length=50)
    private String id2;
    ….
    }

    Your reply would be very much appreciated.

    • uaihebert Post author

      Hello Michael,

      You could do by equals:

      EmbeddedIdDummy idDummy = new EmbeddedIdDummy(1, "01");
      EasyCriteria easyCriteria = EasyCriteriaFactory.createQueryCriteria(getEntityManager(), MyEntity.class);
      easyCriteria.andEquals("id", idDummy);
      List
      resultList = easyCriteria.getResultList();

      I just did the test here and it worked.

      If your implementation is OpenJPA there is an opened bug related to embedded id: https://issues.apache.org/jira/browse/OPENJPA-1806

      Thanks for passing by.

      • Michael Encarnacion

        Hello Hébert,

        thank you for your reply. I haven’t thought of that.
        As a follow up, if my Embedded PK has two fields, (ie id, tenantid), how would I do a like query only for “id” and not included ‘tenantid’.

        Thank you always for your help :)

        • uaihebert Post author

          Hello Michael,

          Thanks for your response, so far this is not supported YET.

          I try will add to it in the next release.

          Thanks for passing by.

  2. Ismael

    Hi, congratulations for you effort with EasyCriteria.

    I am triying it in my project, it’s great, but i have found myself with a problem when i want build a query of type: … where lower(field) like ?

    I don’t find something in the API for build a lower clause…

    Thanks!

    • uaihebert Post author

      Hello,

      EasyCriteria does not have this feature yet.

      But it will have in the next release.

      Thanks for the support.

  3. Yannick Majoros

    Hello Hébert,

    My point is that your complaint, “JPA Criteria should be easy”, should be addressed by telling the JPA expert committee. They did ask for community feedback on the next version. That’s the JCP/JSR process, you can check it or ignore it as you wish but this process is a fact, not my sole opinion. Please don’t take it personnally, but I’d really suggest to beginners to use the real thing – this “framework” is full of inaccurate shortcuts. Sorry again for the negative feedback, I just think that beginners should hear them too.

    • uaihebert Post author

      Hello Yannick,

      I am not the kind of person that complains/criticize about something without a solution.

      That is why I do not want and will not talk with JPA team yet. When EasyCriteria is ready I will talk to the JPA about this verbosity problem and show a solution.

      If they want to use my framework, great. If they do not want to use that is fine, a lot of people will want to use it. I will be available to help JPA team if they want to.

      You do not need to apologize for your negative feedback, it does not bother me. It was the first in the midst of hundreds of positive feedbacks.
      FYI I am preparing a new version. [=

      See ya.

  4. Pingback: Articulo: EasyCriteria 2.0 – JPA Criteria should be easy | Las Neuras de Davioth

  5. Yannick Majoros

    The “criteriaQuery.select(root);” line in your example is not required. So is the line before, if you aren’t restricting your selection (where).

    Then, why are you promoting string-based API’s? One of the best feature of the criteria API is it’s type safety, provided by the meta-model. It’s not making writing queries easier, although not as verbose as what you’d suggest. It’s helping making them object-oriented and type-safe.

    The review process for jpa’s next iteration ended a few weeks ago, why didn’t you try to make suggestions there instead of a new reinventing-the-wheel framework (missing the point, btw)?

    • uaihebert Post author

      Hello Yannick, how are you?

      Indeed the select is required when the where is used, but I did not see a criteria without an where clause.

      One thing to have in mind is that metamodel is good, but is hard to those that are starting with JPA Criteria to understand this hard concept.

      I am not reinventing nothing because I have not found a framework like mine, using only string. [=

      But for next versions I want to add the metamodel capability to support both models of query.

      About the JPA review process I never participate in one, and I am always thinking about how to make easier the life of some developers with the current tools.

      Could you provide-me the link so that I can see the new features?

      Thanks for passing by.

      • Yannick Majoros

        Hello Hébert,

        CriteriaQuery can also be used with strings (although I wouldn’t throw away the type-safe goodness). It’s (somewhat) more verbose, but with reasons. Your API makes some simple things simple and difficult things impossible. Typing has been left out. CriteriaQuery isn’t that difficult, really. I don’t think oversimplification helps beginners.

        The difference between something like this and CriteriaQuery is that the latter has been thought out by multiple actors, having to agree (JSR). The process is quite open, and you had the chance to tell your point of view in the public review. In that sense, you reinvented the wheel, not for better. Sorry if this sounds harsh, but I think that it splits the community, and I think this is a bad thing. I think we should focus on knowing existing technologies and standards to improve them or make counter-proposals, rather than dismiss them without knowing them right.

        If you want some links, just look up JPA 2.1, Google is your friend ;-) Here is the JPA 2.1 JSR, but it’s rather complete and technical: http://jcp.org/en/jsr/detail?id=338 . You can also check this: https://blogs.oracle.com/arungupta/entry/jpa_2_1_early_draft .

        • uaihebert Post author

          Hello Yannick,

          That is your opinion and I do respect that, although is not the feedback that I am receiving from the users of the framework.

          I know several juniors developers that did not use JPA Criteria because its complexity. The same way you think it is easy, I with several other developers think that the API is hard to learn and use.

          I believe that when I create this framework I had to have a good knowledge in JPA. I am not splinting it, I am making easier to use it.

          Sorry if I did not google searching for your opinion, but I do not have time available to follow everything that is suggested to me in the blog. If I did not know how to use google, I would not get where I am now. I will not check your links now because I have to study Spring, get ready the material to the post graduation class that I minister classes and write a new post to my blog.

          When I have time I will look at it.

          See you later. \o_

  6. Pingback: Links & reads for 2013 Week 7 | Martin's Weekly Curations

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *