Hibernate / Boolean Fields / MySQL 5.0

There’s a problem persisting boolean fields using Hibernate 3.2.2 to MySQL 5.0, if you allow Hibernate to generate your schema, and you leave Hibernate to generate the schema in the default way. It works fine on MySQL 4.1 and it doesn’t matter if you use boolean (primitive) or Boolean (object) types for the fields.

with a class such as:

public class MyObject {
   protected boolean myField;
   public boolean getMyField() { return myField; }
   public void setMyField(boolean x) { myField = x; }
}

and a Hibernate mapping such as:

<property name="myField" column="my_field" not-null="true" />

and allow Hibernate to generate the schema on startup, e.g. by writing the following in the “hibernate.cfg.xml” file:

<property name="hbm2ddl.auto">create</property>

Against MySQL 4.1 this all works, and the column has the data type tinyint(1). But in MySQL 5.0 the data type is bit(1) (which seems logical enough) but Hibernate then throws the following unhelpful exception upon every insert:

could not insert: [com.company.MyObject]
org.hibernate.exception.DataException: could not insert: [com.company.MyObject]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:77)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
....
Caused by: java.sql.SQLException: Data too long for column 'my_field' at row 1
at ....

The solution is to change the Hibernate mapping for the field to this:

<property name="myField" not-null="true" >
   <column sql-type="BOOLEAN" not-null="true" name="my_field" />
</property>

Then the field is generated as tinyint(1) and then it all works fine again.

4 Responses to “Hibernate / Boolean Fields / MySQL 5.0”

  1. Guy Van Tilborgh Says:

    This is all great but when I use this solution, our Oracle configuration doesn’t work anymore so I guess there must be a better solution because the whole point of hibernate is to be database independant.

  2. Dan Moore Says:

    Thanks for the fix! Adding that ‘column’ element to the config file solved the problem for me.

  3. Stephen M. Kennedy Says:

    I use this in combination with Query Substitutions to create a schema that is more portable across different databases.

  4. Phemelo Says:

    This was very easy to understand, using hibernate_core v3.3.1 the “BOOLEAN” type could not be resolved.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

For inserting HTML or XML please remember to use &lt; instead of <