Wednesday, July 16, 2008

How to Map an Integer Column Value of 0 (zero) to a null, in Hibernate with MySQL Oracle or DB2?

A question I often get is how to map a zero 0 value to a null value in the database.

According to Gavin King, the man behind Hibernate, the way to map 0 to null is to write a UserType that transforms 0 to null, and use that custom UserType as the identified type. Hibernate will not create a schema with default values, so in this case, you're on your own.

Another neat Hibernate trick is to use the nullif function in HQL. It's slick:

from Clazz c where nullif(, 0) is null

If both expressions are equal, null is returned, otherwise the first expression is returned, as you would expect. This simply helps out in the coding for the null or zero values.

Hibernate Forum Topic on Mapping a 0 to a null...

No comments: