Custom Boolean User Type with Hibernate JPA

The ANSI SQL 1999 standard introduced a BOOLEAN data type (although unfortunately only as an optional feature). But to date it still isn’t implemented by most major database systems. As a consequence boolean columns are implemented in various ways. E.g., CHAR columns containing ‘Y’ or ‘N’, or using BIT columns. Subsequently, there is no way for JPA to provide a standardized way of mapping an entity’s boolean fields onto database columns.

Hibernate offers a custom YesNoType for boolean implementations using CHAR(1) columns containing ‘Y’ or ’N’ characters. But for other practices you basically have to provide your own solution. Fortunately, Hibernate offers the possibility of creating your own custom UserType’s. In this blog entry I will give an example of one such custom Boolean UserType.

Recently, I’ve been confronted with a Dutch legacy database schema in which ‘Y’ (for yes) and ‘N’ (for no) are represented by ‘J’ (“ja”) and ‘N’ (“nee”), respectively. This ruled out using Hibernate’s YesNoType. Adding to the complexity was the fact that some of these columns were using CHAR(1) and others using CHAR(2) with a padded space – don’t ask why!

So I ended up writing a custom UserType that allowed me to basically convert the following…


Coding the custom type proved to be fairly straight forward. I just had to implement the interface org.hibernate.usertype.UserType. Dealing with the varying column lengths involved adding the ‘length’ parameter required implementing a second interface – org.hibernate.usertype.ParameterizedType.

Given below is what I did end up with.

One Reply to “Custom Boolean User Type with Hibernate JPA”

Comments are closed.