Saturday, October 25, 2008

Booleans in Hibernate

As the following helpful article (http://www.databasesandlife.com/hibernate-boolean-fields-mysql-50/) points out:

"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". The problem is, by default, it generates a MqSQL field of type "bit(1)" - which causes Hibernate to throw:

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

When I try to save.

That's causing my tests to fail… so what to do?

Well the article I mention above suggests mapping the field using

<column sql-type="BOOLEAN" />,

which does work.

However, I'm using annotations, so my preferred mapping for booleans is:

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

An alternative is to use:

@Column
private Boolean exampleBooleanValue;

But I prefer to work with primitives rather than boxed primitives wherever possible.
Anyway, the first solution above works wonderfully.

No comments: