Mapping Smallint, Tinyint or Int Column to Boolean in Hibernate

If you have a column in your database which may only contain the value 0 or 1 (i.e. a bit value), you probably want to map it to the boolean static type in your entity, rather than an integer. This could be the case for smallint, tinyint(1), int(1), boolean columns, etc. I found two suggestions on how to do this, but only one of them worked for me. One of the suggestions is to use the columnDefinition attribute of the @Column annotation as follows: @Column(name = “is_active”, columnDefinition=”TINYINT(1)”). Unfortunately, that did not work for me. Instead, Hibernate’s @Type parameter turned out to work, and it can be used as follows.

public class User {
	// ...

	@Column(name = "is_active", nullable = false)
	@Type(type = "org.hibernate.type.NumericBooleanType")
	private boolean isActive;
	// Getters and setters

I have verified that the above works with Hibernate 4.3.7, but it should work with other recent versions of Hibernate as well. The downside to this solution is that it is Hibernate specific, as the @Type annotation does not exist in JPA. As a result, some abstraction is lost, and we couple our entity to our specific JPA provider – Hibernate in this case. The columnDefinition attribute of the @Column annotation, however, is supported by JPA, but for some reason it did not work for me. I urge you to see if this approach works on your particular setup, because abstracting from the specific JPA provider is always preferred. But if it does not work, then at least you have a solution to the problem now, provided that you are using Hibernate as your JPA provider.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *