buzz (1) [Avatar] Offline
#1
In chpater 6, p204 the code fails under hibernate 3.1.3 and 3.2.0cr.

In particular the code for an enumerated type on p210 does not take advantage of the enum types of JDK5.0 - which leads to a cleaner implementation, and also suffers the problem of failing reload.

So ...take a standard enum...

public enum Gender
{
MALE,
FEMALE
}

The hibernate UserType mapping looks like this...


public class GenderUserType implements UserType
{
private static final int[] SQL_TYPES = { Types.VARCHAR };

public int[] sqlTypes()
{
return SQL_TYPES;
}

public Class returnedClass()
{
return Gender.class;
}

public Object nullSafeGet(ResultSet arg0, String[] arg1, Object arg2) throws HibernateException, SQLException
{
String colStr = arg1[0];
int colNum = arg0.findColumn(colStr);
String item = arg0.getString(colNum);

return arg0.wasNull() ? null : Gender.valueOf(item);
}

public void nullSafeSet(PreparedStatement arg0, Object arg1, int arg2) throws HibernateException, SQLException
{
if (arg1 == null)
{
arg0.setNull(arg2, Types.VARCHAR);
}
else
{
arg0.setString(arg2, arg1.toString());
}
}

....
and so on with the remaining functions that must be overriden.

Now the problem comes with reloading from the database - the code uses findColumn() to obtain the index before calling getString(). This is becuase hibernate returns column names like 'gender0_' and getString() fails to match this. Calling findColumn() with the aliased name, and then calling getString() with the index solves the problem.

The cleaner code comes from the use of the .toString() and .valueOf() methods of Enum which provide string conversion without having to create a 'synthetic' enum.

Just thought Id share it to stop someone else hunting round for 6hrs!

The above has been tested with Hibernate 3.1.2/3.1.3 and 3.2.0cr1 talking to Apache Derby 10.1.2.1 and MySQL 5.0.18.