• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dynamic named queries

 
Ronan Dowd
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I'm using hibernate v3.2.1 and am using named queries
My query is:
select name from customer where age = :theAge and address = :theAddress and gender = :theGender

My java code is:
Query query = getSession().getNamedQuery("getCustomer");
query.setString("theAge", "10"); //the only mandatory fied
query.setString("theAddress", "Cork");
query.setString("theGender", "M");

This works fine as long as age, adddress and gender are passed into the query. But the user might only
pass in the age (and not set address and gender at all). Hiberate will complain that these parameters aren't set.
Is there any way to make this named query "dynamic", i.e. if only the age is passed in then only that is
user in the query ? Or would i need to restructure my query to cope with null values?
Cheers. Ro
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the only way is to use a dynamic filter (or restructure your query). Named queries don't support nullable parameters.

Unfortunately I don't think you can do the old trick of writing a query like "where param = 'blah' or [bound_value] is null" - if memory serves me right this results in a syntax error.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic