自定义ORM(mybatis)源码(六)-类型处理器
模仿mybatis
用于处理 sql 设置参数类型和 执行 sql 后响应字段的类型处理
TypeHandler
public interface TypeHandler<T> {/*** sql 设置参数值* @param pstmt* @param i* @param value* @throws SQLException*/void setParameter(PreparedStatement pstmt, int i, T value) throws SQLException;/*** sql 执行结果获取字段* @param rs* @param columnName* @return* @throws SQLException*/T getResult(ResultSet rs, String columnName) throws SQLException;
}
TypeHandlerRegister
类型注册
public class TypeHandlerRegister {private static Map<Class<?>, TypeHandler<?>> handlerMaps = new ConcurrentHashMap<>();static {handlerMaps.put(Integer.class, new IntegerTypeHandler());handlerMaps.put(String.class, new StringTypeHandler());handlerMaps.put(Long.class,new LongTypeHandler());}/*** 根据 类型获取 类型处理器* @param claz* @return* @param <T>*/public static <T> TypeHandler<T> getHandler(Class<T> claz){return (TypeHandler<T>) handlerMaps.get(claz);}
}
现有:
- IntegerTypeHandler
- LongTypeHandler
- StringTypeHandler
如 LongTypeHandler:
public class LongTypeHandler implements TypeHandler<Long> {@Overridepublic void setParameter(PreparedStatement pstmt, int i, Long value) throws SQLException {pstmt.setLong(i, value);}@Overridepublic Long getResult(ResultSet rs, String columnName) throws SQLException {return rs.getLong(columnName);}
}