This is the same question as:
How to dynamically generate SQL query based on user's selections?
The only difference is, that I\'m interested in seeing soluti
I use the Querydsl framework because I'm using JPA 1.0 which does not include the Criteria API and I also needed the features you described. Writing Querydsl code is easy and the code is shorter than Criteria API code. Querydsl is free to use and it supports typesafe queries.
There are many different tools the best i think are querydsl, torpedoquery e Object Query, this three allow to write typesafe query, otherwise you can use criteria api, and if you are using jpa 2 also JPA2 Typesafe Query.
with all this tools you can build a query at runtime!!
If you want to do this in JPA 1.X, you can use custom query builder as described here http://rrusin.blogspot.com/2010/02/jpa-query-builder.html. This enables creating queries like this:
return new JpaQueryBuilder().buildQuery(em,
new Object[] {
"select c from Car c where c.name is not null",
new JQBParam("name", name, " and c.name = :name"),
new JQBParam("type", type, " and c.type = :type")
}
)
In Hibernate, you can use Criteria queries.
In Toplink, we got Expression, and ExpressionBuilder.
In my code, I'm using AND
and OR
objects for this. They take lists as parameters (looks nice with Java 5's variadic arguments) and concatenate them in Strings with the necessary spaces and parentheses. Pseudo code:
AND(WhereCond ... conds) { this.conds = conds; }
toString() { return conds.length == 0 ? "" : "(" + join(conds, " AND ") + ")" };
where join()
converts the object array to string array and then joins the elements with the parameter.