万恶的Mybatis的EnumTypeHandler
程序员文章站
2022-06-07 12:59:46
...
项目里面使用了Mybatis,然后里面一些POJO有使用到Enum的情况,在数据库里面的字段类型是SMALLINT,然后再Mybatis里面不能正确的转换。然后我在网上找了下,提到了EnumTypeHandler,那我们就来看这个TypeHandler的实现吧:
我们主要来看上面的setNonNullParameter方法,看到它是转换为字符串设置了,那我们用它的这个TypeHandler当然不行了,就想到自定义吧。
Mybatis在实现TypeHandler的时候,是直接调用的EnumTypeHandler的构造函数,但是注册其他的TypeHandler都是调用无参数的构造函数。
最后没有办法,我只能每个Enum,写一个TypeHandler,因为在typeHanderl里面没有办法拿到JavaType. 当然了大家如果有什么好的办法也欢迎交流讨论。
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); } }
下一篇: “哈哈哈哈!老公