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. Continue reading “Custom Boolean User Type with Hibernate JPA”

Gotcha: preserving the ordering in collections when using JPA

This week I was faced with the requirement to store the ordering of a collection from a Java web application to a database. In plain Java, retaining the ordering within a collection is a no-brainer: you just use one of the java.util.List implementations. And saving the order into a database table should be as easy as a couple of INSERT statements in the correct order, right? Well, if you’re using JPA for ORM then it really isn’t that straightforward. As it turns out JPA does not take the ordering of a List into consideration, which imho is a serious design flaw. Forunately, as of version 2.0 a workaround was added to the spec: you can annotate relationships with @OrderColumn.