Details
-
New Feature
-
Status: Open
-
Major
-
Resolution: Unresolved
-
3.0 Beta 9
-
None
-
None
Description
In some cases it would be useful to have base class for enum TypeHandlers, that allow to store enumerations to the database by their ordinal() value. Code might look like this:
/**
- This class converts enumeration type into the database form by ordinal value (and back again).
*/
public abstract class EnumOrdinalTypeHandler extends BaseTypeHandler {
private final Class type;
private final Method values;
protected EnumOrdinalTypeHandler(Class type) {
this.type = type;
try
catch(Exception ex)
{ throw new IllegalArgumentException("Class " + type.getSimpleName() + " is not an enumeration class.", ex); }}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
int i = rs.getInt(columnName);
if(rs.wasNull())
try { Object[] enums = (Object[])values.invoke(null); return enums[i]; } catch (Exception ex) { throw new IllegalArgumentException( "Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex ); }
}
}
@Override
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
int i = cs.getInt(columnIndex);
if(cs.wasNull()) { return null; }
else {
try
catch (Exception ex)
{ throw new IllegalArgumentException( "Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex ); } }
}
}
Code is tested and functional.