聊聊Mybatis的类型转换接口TypeHandler

网友投稿 845 2022-10-21

聊聊Mybatis的类型转换接口TypeHandler

聊聊Mybatis的类型转换接口TypeHandler

mybatis可以实现jdbc类型和java类型之间的转换,具体来说有一个类型转换器的接口:

类型处理器接口TypeHandler

TypeHandler

public interface TypeHandler { void setParameter(PreparedStatement ps, int throws; /** * @param T getResult(ResultSet rs, String columnName) throws; T getResult(ResultSet rs, int throws; T getResult(CallableStatement cs, int throws;}

类型处理器BaseTypeHandlerjdbc类型转为java类型

BaseTypeHandler实现了TypeHandler接口,实现了setParameter()方法:

@Override public void setParameter(PreparedStatement ps, int throws{ if (parameter == null) { if (jdbcType == null) { throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters."); } try { ps.setNull(i, jdbcType.TYPE_CODE); } catch (SQLException e) { throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " + "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " + "Cause: " + e, e); } } else { try { setNonNullParameter(ps, i, parameter, jdbcType); } catch (Exception e) { throw new TypeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . " + "Try setting a different JdbcType for this parameter or a different configuration property. " + "Cause: "

这个方法中就是设置PreparedStatement的参数,也是参数绑定,将jdbcType转为Java类型,setNonNullParameter是抽象方法,根据不同的参数类型有不同的类实现了这个方法,比如LongTypeHandler实现的setNonNullParameter()方法:

@Override public void setNonNullParameter(PreparedStatement ps, int throws{ ps.setLong(i, parameter); }

java类型转为jdbc类型

BaseTypeHandler的getResult()方法:

@Override public T getResult(CallableStatement cs, int throws{ try { return getNullableResult(cs, columnIndex); } catch (Exception e) { throw new ResultMapException("Error attempting to get column #" + columnIndex + " from callable statement. Cause: "

方法也比较简单,直接调用了getNullableResult抽象类,功能就是从ResultSet中获取数据,把Java类型转换为JdbcType类型,比如LongTypeHandler实现的getNullableResult():

@Override public Long getNullableResult(ResultSet rs, String columnName) throws{ long result = rs.getLong(columnName); return result == 0 && rs.wasNull() ? null

通过源码分析我们知道了TypeHandler接口的作用就是用来实现类型转换的,mybatis在初始化的时候就获取TypeHandler,然后创建TypeHandler实例注册到TypeHandlerRegistry中,由TypeHandlerRegistry来进行管理这些实例,下篇文章中我们介绍一下TypeHandlerRegistry这个类

总结

这篇文章讲了Mybatis的类型转换接口TypeHandler和它的实现类BaseTypeHandler,类型转换接口显然就是实现jdbc类型和java类型之间的转换,同时分析了BaseTypeHandler的setParameter()方法和getResult()方法,getNullableResult是抽象类,具体方法由其他实现类进行实现。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:openhandx batch- 异步批量调度框架
下一篇:浅谈String类型如何转换为time类型存进数据库
相关文章

 发表评论

暂时没有评论,来抢沙发吧~