Tuesday, April 26, 2011

Hibernate, enumerations and smiley faces

I have a database table that has a column with single character values that are pre-defined. In the application tier, they are mapped as enumerations. So, it can be of value 'A', 'B', 'C' let's say.

Hibernate works well with that when I have to do something like
SELECT * FROM table WHERE columnX = 'A'; 

I use the CriteriaQuery to generate an instance of the object, add the column name, eq, value and viola, I am good to go. I would get an instance of whatever object the table maps to. Great. Keep in mind that my query is a bit more complex (column1 = blah and column2 = blah1 and columnX = 'A').

Now let's say I want to make this somewhat more flexible. In some cases, I need to do this
SELECT * FROM table WHERE columnX = '_'; 

How do I do that with hibernate (given that I am trying to use the enum for the value portion of the Criteria)?

The best I was able to come up with was to pass in null and check in my query creation method whether the passed in value was null; if so, then don't add it to the query (match any single character for a single character column should be the same as not passing in that where clause). Is there a better way of doing that?

No comments: