Dynamically build the query depending on whether the values are null/empty/zero or not?
Code:
StringBuffer buffer = new StringBuffer("select u from Usedmachine as u inner join u.Category as Category");
if ( (this.type != null && !this.type.equals("")) || (this.year != null && this.year.intValue() > 0) ) {
buffer.append(" where");
if (this.type != null && !this.type.equals("")) {
buffer.append(" u.Typ=:typ");
if (this.year != null && this.year.intValue() > 0) {
buffer.append(" and");
}
}
if (this.year != null && this.year.intValue() > 0) {
buffer.append(" u.Sellyear=:year");
}
}
Query query = session.createQuery(buffer.toString());
if (this.type != null && !this.type.equals("")) {
query.setString("typ",this.type);
}
if (this.year != null && this.year.intValue() > 0) {
query.setInteger("year",this.year);
}
This is REALLY ugly, I'd admit. I hate all those nested if statements. You could also do something cleaner and clearer with criteria queries. In fact, perhaps you should build a criteria query based on whether your parameters are null or not.
Code:
Criteria criteria = session.createCriteria(Usedmachine.class);
if (this.type != null && !this.type.equals("")) {
criteria.add(Restrictions.eq("typ", this.type);
}
if (this.year != null && this.year.intValue() > 0) {
criteria.add(Restrictions.eq("year", this.year);
}
List list = criteria.list();
Isn't that cleaner?