package org.apache.ibatis.type; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class EnumTypeHandler extends BaseTypeHandler implements TypeHandler { private Class type; public EnumTypeHandler(Class type) { this.type = type; } public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, parameter.toString()); } public Object getNullableResult(ResultSet rs, String columnName) throws SQLException { String s = rs.getString(columnName); return s == null ? null : Enum.valueOf(type, s); } public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String s = cs.getString(columnIndex); return s == null ? null : Enum.valueOf(type, s); } }
我们主要来看上面的setNonNullParameter方法,看到它是转换为字符串设置了,那我们用它的这个TypeHandler当然不行了,就想到自定义吧。
Mybatis在实现TypeHandler的时候,是直接调用的EnumTypeHandler的构造函数,但是注册其他的TypeHandler都是调用无参数的构造函数。
public TypeHandler getTypeHandler(Class<?> type, JdbcType jdbcType) { Map<JdbcType, TypeHandler> jdbcHandlerMap = TYPE_HANDLER_MAP.get(type); TypeHandler handler = null; if (jdbcHandlerMap != null) { handler = jdbcHandlerMap.get(jdbcType); if (handler == null) { handler = jdbcHandlerMap.get(null); } } if (handler == null && type != null && Enum.class.isAssignableFrom(type)) { handler = new EnumTypeHandler(type); } return handler; }
最后没有办法,我只能每个Enum,写一个TypeHandler,因为在typeHanderl里面没有办法拿到JavaType. 当然了大家如果有什么好的办法也欢迎交流讨论。
public class ProcessStateTypeHandler extends BaseTypeHandler implements TypeHandler { public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { ps.setInt(i, ((ProcessState)parameter).ordinal()); } public Object getNullableResult(ResultSet rs, String columnName) throws SQLException { Integer s = rs.getInt(columnName); return s == null ? null : ProcessState.fromValue(s); } public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { Integer s = cs.getInt(columnIndex); return s == null ? null : ProcessState.fromValue(s); } }