File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Using Named Queries Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Using Named Queries" Watch "Using Named Queries" New topic

Using Named Queries

Kim Kantola
Ranch Hand

Joined: May 17, 2001
Posts: 276
Hi Yall,
I am starting to use named queries, and am not sure how to handle one thing. I have a query like "from myTable". If the user passes in a firstName, or lastName, or Date of birth, the query should be however, at runtime, I am not sure if the user is going to pass any or all of the parameters.

I want to have this query defined in my file NamedQuery.hbm.xml

I just don't know how to handle deciding on the fly if I need to remove one of the things like lname = :lastName from my query.

Can I do something like this in the code (use a wildcard)

Thanks if anyone has an idea.
Andreas Erber

Joined: Oct 03, 2009
Posts: 20
Hi Kim Kantola,

I've never used named queries myself but my first guess is if you want to use a wildcard you should probably try the SQL-wildcard of your DBMS. That is, most likely, the per-cent sign "%".


Kim Kantola
Ranch Hand

Joined: May 17, 2001
Posts: 276
Thank you very much, yes, using the "%" did the trick.

It however brought me to a new problem, one of the fields I am trying to compare is a date, so if I have this in my query:

as part of my query, and my DOB value is null so I do this :

I then get the follwing error :

at org.hibernate.type.DateType.toString(
at org.hibernate.type.NullableType.nullSafeSet(
at org.hibernate.type.NullableType.nullSafeSet(
at org.hibernate.loader.hql.QueryLoader.bindNamedParameters(

Is there a special wildcard to use for dates ?

Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

Usually for queries which are dynamic like that, it is easier to use the Criteria object instead.

then you can have code like

from myTable where fname= :firstName AND lname= :lastName and DOB =OB


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
I agree. Here's the link:
subject: Using Named Queries
It's not a secret anymore!