Mysql – Hibernate, Null values and nativeSQL


I'm using hibernate with mySQL and I've the following problem: I do a nativeSQL query on a table with, among others, a column that is a character long. This column can get to null. Now I receive the following exception while querying:

4-feb-2010 10.31.00 org.hibernate.type.NullableType nullSafeGet
INFO: could not read column value from result set: nazeuro; String index out of range: 0
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        at java.lang.String.charAt(
        at org.hibernate.type.CharacterType.get(
        at org.hibernate.type.NullableType.nullSafeGet(
        at org.hibernate.type.NullableType.nullSafeGet(
        at org.hibernate.loader.custom.CustomLoader$ScalarResultColumnProcessor.extract(
        at org.hibernate.loader.custom.CustomLoader$ResultRowProcessor.buildResultRow(
        at org.hibernate.loader.custom.CustomLoader.getResultColumnOrRow(
        at org.hibernate.loader.Loader.getRowFromResultSet(
        at org.hibernate.loader.Loader.doQuery(
        at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(
        at org.hibernate.loader.Loader.doList(
        at org.hibernate.loader.Loader.listIgnoreQueryCache(
        at org.hibernate.loader.Loader.list(
        at org.hibernate.loader.custom.CustomLoader.list(
        at org.hibernate.impl.SessionImpl.listCustomQuery(
        at org.hibernate.impl.AbstractSessionImpl.list(
        at org.hibernate.impl.SQLQueryImpl.list(
        at Views.Components.QuickLookup$

I've been googling to solve the issue, I even found posts here on SO, but everytime it is about mapping to objects and writing custom classes to handle the issue. In this situation what I need is a Object array. I know a solution could be to change the table but I'd avoid it as I've to work with a pre-existing db. So do you have any possible solutions?

SQLQuery query = sess.createSQLQuery("SELECT * from " + table + " WHERE " + filter + " LIKE '" + search + "%'");
                    List<Object[]> result = query.list();

Best Solution

Which Hibernate version are you using? In 3.3.2, this is CharacterType.get():

public Object get(ResultSet rs, String name) throws SQLException {
    String str = rs.getString(name);
    if (str==null) {
        return null;
    else {
        return new Character( str.charAt(0) );

In case this wasn't obvious, the exception indicates that you got an empty, non-null string ("") from the result set, which causes CharacterType to barf, as this is not an expected value for a CHAR(1). (This is a CHAR(1) column, is it?)

Related Question