I have search screen which has 10 fields and involves around 5 to 6 tables to get the result. I am writing a custom SQL query and appending where condition only when a value exists.
Can someone please suggest is this the right approach or any other better way.
I cannot use any plugins or additional APIs for my situation.
StringBuffer sqlQuery = new StringBuffer();
sqlQuery.append (" select member.* from member, customer, case where customer.status='A');
if(firstName != null)
sqlQuery.append("customer.firstName= :firstName");
if(caseid != null)
sqlQuery.append("case.caseid =:caseid");
SQLQuery queryObj = createSQLquery(sqlQuery.toString());
queryObj.list();
where as member, customer, case are actual tables.
UPDATE
when I am adding where condition to string buffer
if(caseid != null)
sqlQuery.append(" and case.caseid =:caseid");
and when queryObj is formed I am doing it as
if(caseid != null)
queryObj.setString("caseid", caseid);
is there better way to add after queryObj (to combine both)?
Thanks in advance.
No, it’s not necessarily the right approach. SQL is not the query language of choice when using Hibernate. HQL should be preferred when possible. And Hibernate also has the Criteria API which has been designed precisely to build dynamic queries.