views:

29

answers:

1

I have a web app build with Hibernate. In one page, I have one submit button with 5 inputs

  • field1
  • field2
  • field3
  • field4
  • field5

When all the inputs are null, I make a simple querry

Query query = session.createQuery("from MyTable");

but when I have at least one input not null, I must create the search query. Let's say, the field1 is not null:

Query query = session.createQuery("from MyTable where field1= :field1");
query.setParameter("field1", field1);

But I need to check every single input and I need to create the query String based on this thing.

What is the smartest, easiest way to create the search query?

A: 

You could use a Criteria-Query instead:

Criteria criteria = hibernateSession.createCriteria(YourClass.class);

And then add a Criteria to your query based on every field:

if(fieldValue1 != null) {
    criteria.add(Restrictions.eq("FieldProperty1", fieldValue1))
}

if(fieldValue2 != null) {
    criteria.add(Restrictions.eq("FieldProperty2", fieldValue2))
}

...

Of course, that will only work if you use the native hibernate API instead of the JPA-API.

Imion