enum类型不是标准的jdbcType, 所以你要使用
type handler配置一下映射。数据库里使用varchar类型,存储enum字段的name .
/**
* ibatis内置了一个EnumTypeHandler,
* 但它没有无参构造函数,直接使用它会导致java.lang.InstantiationException, 所以你要另建一个类,提供一个无参构造函数,并利用装饰器模式集成EnumTypeHandler的功能。
* ibatis内置的EnumTypeHandler还有一个缺点: 对于数据库里存储的脏数据即不在指定enum
* name范围之内的数据,EnumTypeHandler在运行时会直接报异常; 但在一般的应用场景下,我们希望把这些脏数据解析成null就可以了。
* 所以,我们的新类里应该在这方面提供健壮性。
*
* 用法:对每个具体的枚举,请继承一下本类
*
* @author kent
*
*/
@SuppressWarnings("rawtypes")
public abstract class MyEnumTypeHandler extends BaseTypeHandler implements TypeHandler {
private EnumTypeHandler delegate;
public MyEnumTypeHandler() {
Class type = this.getEnumType();
delegate = new EnumTypeHandler(type);
}
public abstract Class getEnumType();
public void setParameter(PreparedStatement ps, int i, Object parameter,
String jdbcType) throws SQLException {
try {
delegate.setParameter(ps, i, parameter, jdbcType);
} catch (Exception e) {
}
}
public Object getResult(ResultSet rs, String columnName)
throws SQLException {
try {
return delegate.getResult(rs, columnName);
} catch (Exception e) {
return null;
}
}
public Object getResult(ResultSet rs, int columnIndex) throws SQLException {
try {
return delegate.getResult(rs, columnIndex);
} catch (Exception e) {
return null;
}
}
public Object getResult(CallableStatement cs, int columnIndex)
throws SQLException {
try {
return delegate.getResult(cs, columnIndex);
} catch (Exception e) {
return null;
}
}
public Object valueOf(String s) {
try {
return delegate.valueOf(s);
} catch (Exception e) {
return null;
}
}
}