I'm using native query API. But it is usual to apply dynamic filters, ordering and limiting first and maxResults of a query. Criteria interface is ideal for that. I have written small utility class to apply critetia query restrictions to native query. Here is usage code sample
CriteriaParams critPar = new CriteriaParams();
critPar.add(Restrictions.eq("P.FULLNAME", "Doe"));
critPar.addOrder(Order.asc("P.SHORTNAME"));
CriteriaSQL csql = new CriteriaSQL(critPar);
SQLQuery q = hs.createSQLQuery(csql.getQueryString("SELECT P.* FROM PERSON P, CLIENT C WHERE P.ID = C.PERSONID "))
.addEntity(Person.class);
csql.populateParams(q);
List result = q.list();
The resulting sql in this case will be
SELECT P.* FROM PERSON P, CLIENT C WHERE P.ID = C.PERSONID
AND P.FULLNAME = ? ORDER BY P.SHORTNAME ASC
So CriteriaSQL class generates full sql statement using Criteria restrictions, order, first and maxResults. It uses hibernate toSqlString functions. It also sets restriction parameters to resulting SQLQuery.
CriteriaParams is also my simple detached criteria container. It is used to store criteria parameters.
So please comment my approach. How do you solve the problem of native query and dynamic restrictions?
If someone is interested in source code I'm ready to publish it. Don't know is it Ok to post it just here in forum.
|