views:

539

answers:

1

Is there any way to specify optional parameters (such as when search parameters are provided from a form and not all parameters are required) in a named query when using Hibernate? I'm using a native SQL query, but the question is probably applicable to named HQL queries as well.

I'm pretty sure the answer to this is 'no', but I haven't found the definitive answer in the documentation yet.

+2  A: 

AFAIK, there is no such thing so you'll have to write a dynamic query for this. Maybe have a look at this previous answer showing how to do this in HQL (that you can transpose to SQL) and also showing how the Criteria API makes it simpler and is thus better suited for this job in my opinion.

Update: (answering a comment from the OP) Working with a legacy database can be indeed tricky with Hibernate. Maybe you can use a dynamic native query and return non-managed entities though. But on the long run, things might get worse (I can't tell that for you). Maybe Hibernate is not the best choice in your case and something like iBATIS would give you the flexibility you need.

Pascal Thivent
Thanks. That's pretty much what I figured. I'm familiar with both of the approaches you suggested in your other answer, but I'm stuck with a nightmarish legacy db schema that just isn't well suited to the Hibernate approach for my particular case. I've made it work so far, but have some new requirements I just can't seem to meet using straight Hibernate mapping. I'm probably going to give up and use iBATIS for this one case. Not real thrilled adding another technology to the stack as a band-aid, but that's life I guess. Thanks.
Ickster
@Ickster See my update.
Pascal Thivent
@Pascal Thanks for the update. I've considered that approach as well and given the number of parameters I'm dealing with, I decided it's probably cleaner to just use iBATIS. Thanks for the advice.
Ickster