Mapping Smallint, Tinyint or Int Column to Boolean in Hibernate

Published on March 26, 2015 by

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.

@Entity
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.

Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

One comment on »Mapping Smallint, Tinyint or Int Column to Boolean in Hibernate«

  1. Rickson

    I tried the above for native queries

    Query query = sess.createSQLQuery(sqlQueryStr)
    .setResultTransformer(Transformers.aliasToBean(instance.getClass()));

    Neither ColumnDefinition nor Type worked for me. I had to just create a separate DTO class to handle it.

Leave a Reply

Your e-mail address will not be published.