萬(wàn)惡的Mybatis的EnumTypeHandler
JavaSQLiBATISApache
項(xiàng)目里面使用了Mybatis,然后里面一些POJO有使用到Enum的情況,在數(shù)據(jù)庫(kù)里面的字段類(lèi)型是SMALLINT,然后再M(fèi)ybatis里面不能正確的轉(zhuǎn)換。然后我在網(wǎng)上找了下,提到了EnumTypeHandler,那我們就來(lái)看這個(gè)TypeHandler的實(shí)現(xiàn)吧:
Java代碼
- 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);
- }
-
- }
我們主要來(lái)看上面的setNonNullParameter方法,看到它是轉(zhuǎn)換為字符串設(shè)置了,那我們用它的這個(gè)TypeHandler當(dāng)然不行了,就想到自定義吧。
Mybatis在實(shí)現(xiàn)TypeHandler的時(shí)候,是直接調(diào)用的EnumTypeHandler的構(gòu)造函數(shù),但是注冊(cè)其他的TypeHandler都是調(diào)用無(wú)參數(shù)的構(gòu)造函數(shù)。
Java代碼
- 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;
- }
最后沒(méi)有辦法,我只能每個(gè)Enum,寫(xiě)一個(gè)TypeHandler,因?yàn)樵趖ypeHanderl里面沒(méi)有辦法拿到JavaType. 當(dāng)然了大家如果有什么好的辦法也歡迎交流討論。
Java代碼
- 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);
- }
-
- }