Wednesday, July 9, 2008

Hibernate - Mapping booleans using annotations.

Summary:
Using Hibernate annotations to map a Java boolean in MySQL.

The Problem:

I've recently experienced some problems with mapping boolean values in a Hibernate entity to mySQL. The problem arose because the "boolean" type in mySQL is not actually a boolean. It's a tinyint.

MySQL does support the SQL Standard BOOLEAN or BOOL keywords, but treats these as synonyms for TINYINT(1). A value of zero is considered false. Non-zero values are considered true.


The solution:

Luckily, this isn't a problem for Hibernate, once you know what you're doing. Indeed, if Hibernate is creating your database, all you need to do is annotate your booleans with correct annotations, namely:

@Column(columnDefinition = "tinyint", nullable = false)
boolean myTrueOrFalseValue;

or, if you need to allow potentially null columns:

@Column(columnDefinition = "tinyint")
Boolean myTrueOrFalseValue;

Both of these will work, however the first one does not allow null values.

WARNING: This means that if you have been trying a number of different attempts to map "myTrueOrFalseValue" you'll probably already have a column in your mySql table and it will be full of null values. You'll need to delete this column manually (and allow hibernate to regenerate), or use some other manual method to ensure there are no null values in the column. If you do have null values in your database, these annotations will cause a "
org.hibernate.PropertyAccessException: could not set a field value by reflection setter of..." error on startup.

1 comment:

Anonymous said...

This was very helpful. Thanks for posting.