publicEnumValueHandler(Class<E> type){ if (type == null) thrownew IllegalArgumentException("type不得为null"); this.type = type; E[] enums = this.type.getEnumConstants(); this.codeToEnum = new HashMap<>(enums.length); for (E e : enums) { this.codeToEnum.put(e.getCode(), e); } }
@Override publicvoidsetNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType)throws SQLException { ps.setInt(i, parameter.getCode()); }
@Override public E getNullableResult(ResultSet rs, String columnName)throws SQLException { int value = rs.getInt(columnName); if (rs.wasNull()) { returnnull; } return codeToEnum.get(value); }
@Override public E getNullableResult(ResultSet rs, int columnIndex)throws SQLException { int i = rs.getInt(columnIndex); if (rs.wasNull()) { returnnull; } else { return codeToEnum.get(i); } }
@Override public E getNullableResult(CallableStatement cs, int columnIndex)throws SQLException { int i = cs.getInt(columnIndex); if (cs.wasNull()) { returnnull; } else { return codeToEnum.get(i); } }
}
将自定义个TypeHandler注册到MyBatis
1 2 3 4 5 6 7
@Bean public SqlSessionFactory sqlSessionFactory()throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); // .... sqlSessionFactoryBean.setTypeHandlersPackage("cn.com.weidai.rdc.dao.handler"); return sqlSessionFactoryBean.getObject(); }