4

Do you know a way of implementing something like a Hibernate QBE (Query by Example) in JPA?

For my problem domain the alternative of using it will be to build a SQL query dynamically using some sort of string manipulation, something I would like to avoid.

I know this is not supported by default in the API, but I recognize it as a great technique for building dynamic queries.

Any suggestions?

Myles Gray
  • 8,711
  • 7
  • 48
  • 70
Jose Diaz
  • 5,353
  • 1
  • 31
  • 29

4 Answers4

9

QBE is not available in JPA 1.0 or 2.0. For more details look here

Community
  • 1
  • 1
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
  • 1
    I think this is the correct answer but unfortunately it is in the hands of the OP to pick the right one. I upvoted yours. – SkyWalker Dec 21 '12 at 14:23
8

In JPA 2.0 the closest equivalent is called the Criteria API. It did not exist in JPA 1.0.

Here is a sample:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery c = cb.createQuery(Person.class);
Root person = c.from(Person.class);
c.select(person)
    .where(cb.equal(person.get("name"), "Officer Friendly"));
Jim Tough
  • 14,843
  • 23
  • 75
  • 96
  • Thank U very much for the example, thats the thing, I'm not using JPA 2.0 but 1.0 – Jose Diaz Nov 20 '10 at 06:58
  • 2
    One of the main advantages of FindByExample is that you are free to refactor the entity without having to worry about breaking the queries that rely on FindByExample. In this example you see that if Person "name" gets refactored splitting it into "firstName" and "lastName" the query will be broken. – SkyWalker Dec 21 '12 at 14:21
1

I was in facing this same issue a while back.

I found that using the JPA Criteria API was a bit cumbersome, so I decided to make an abstraction on top of it.

It is a small, flexible and simple library: https://github.com/kenglxn/QueryByExample

Hopefully it can be useful for others with this same issue.

The test case has several practical examples: https://github.com/kenglxn/QueryByExample/blob/master/src/test/java/net/glxn/qbe/QBETest.java

kenglxn
  • 1,890
  • 2
  • 14
  • 10
0

A long time ago i had to scratch that ich and i decided to do it myself.

you can get it at sourceforge: svn://svn.code.sf.net/p/jpaco/code/ jpaco-code

Monachus
  • 194
  • 2
  • 9