A very common situation is to have conditions in a query that sometimes should apply and sometimes should not. The common example for this sort of thing is a search page with multiple criteria.
Hibernate currently allows you to support a complex situation like this in one of two ways. 1) You can dynamically build your HQL query string in your java code, or 2) you can use the Criteria API, also in your java code.
Hibernate does not currently provide a means of supporting complex criteria queries using named queries stored in your .hbm files. (If it does, I have not found documentation of this).
It would, I think, be a relatively straighforward matter to leverage the existing named parameters functionality.
My proposal is that a new tag be made available to be used inside of <query> tags to support criteria that may or may not apply. To provide flexability, the tag could be called something like <if>. Here's an example of what I imagine a query might look like:
from Person p
<if condition="paramExists" compare="firstName">
<true>p.firstName = :firstName</true>
<if condition="paramExists" compare="lastName">
<true>p.lastName = :lastName</true>
<if condition="paramExists" compare="beginDate">
<true>p.date >= :beginDate</true>
<if condition="paramExists" compare="endDate">
<true>p.date >= :endDate</true>
order by p.firstName, p.lastName
Clearly, a query such as this could get very complicated. But this is pretty much in the nature of the beast. The current solutions are also complicated and difficult to read and maintain.
The structure above could also be streamlined to something like the following:
<ignore-if-not-set param="lastName">p.lastName = :lastName</ignore-if-not-set>
To me the advantages of such a system are obvious. Instead of having to build your query using code, you could let Hibernate take care of that for you and package your HQL in a consistent and readable fashion instead of burying it in your Java.
Hibernate 3.0 or later