谈谈Mybatis的类型转换接口TypeHandlerMybatis可以实现jdbc类型和java类型的转换。具体来说,有一个类型转换器接口:/***@paramcolumnName列名,当配置useColumnLabel
为false
时*/TgetResult(ResultSetrs,StringcolumnName)throwsSQLException;TgetResult(ResultSetrs,intcolumnIndex)抛出SQLException;TgetResult(CallableStatementcs,intcolumnIndex)throwsSQLException;}typehandlerBaseTypeHandlerjdbc类型转换为java类型BaseTypeHandler实现TypeHandler接口,实现setParameter()方法:@OverridepublicvoidsetParameter(PreparedStatementps,inti,Tparameter,JdbcTypejdbcType)throwsSQLException{if(parameter==null){if(jdbcType==null){thrownewTypeException("JDBC要求必须为所有可为空的参数指定JdbcTypers.");}try{ps.setNull(i,jdbcType.TYPE_CODE);}catch(SQLExceptione){thrownewTypeException("为参数#"+i+"设置null时出错"+jdbcType+"."+"尝试为此参数设置不同的JdbcType或不同的jdbcTypeForNull配置属性。"+"原因:"+e,e);}}else{try{setNonNullParameter(ps,i,parameter,jdbcType);}catch(Exceptione){thrownewTypeException("Errorsettingnonnullforparameter#"+i+"withJdbcType"+jdbcType+"."+"TrysettingadifferentJdbcTypeforthisparameteroradifferentconfigurationproperty."+"Cause:"+e,e);}}}这个方法是设置PreparedStatement的参数,也就是参数绑定,将jdbcType转为Java类型。setNonNullParameter是一个抽象方法,不同的类根据不同的参数类型实现这个方法,比如LongTypeHandler实现的setNonNullParameter()方法:@OverridepublicvoidsetNonNullParameter(PreparedStatementps,inti,Longparameter,JdbcTypejdbcType)throwsSQLException{ps.setLong(i,parameter);}Java类型转换为jdbc类型BaseTypeHandlergetResult()方法:@OverridepublicTgetResult(CallableStatementcs,intcolumnIndex)throwsSQLException{try{returngetNullableResult(cs,columnIndex);}catch(Exceptione){thrownewResultMapException("Errorattempttogetcolumn#"+columnIndex+"fromcallablestatement.Cause:"+e,e);方法也比较简单,直接调用getNullableResult抽象类,作用是从ResultSet中获取数据,将Java类型转换为JdbcType类型,比如LongTypeHandler的实现getNullableResult():@OverridepublicLonggetNullableResult(ResultSetrs,StringcolumnName)抛出SQLException{longresult=rs.getLong(columnName);返回结果==0&&rs.wasNull()?空:结果;知道TypeHandler接口的作用是实现类型转换,mybatis一开始转换时获取TypeHandler,然后创建一个TypeHandler实例注册到TypeHandlerRegistry中,TypeHandlerRegistry会管理这些实例。在下一篇文章中,我们将介绍TypeHandlerRegistry类。总结本文讲的是Mybatis的类型转换接口TypeHandler及其实现ClassBaseTypeHandler,类型转换接口很明显是为了实现jdbc类型和java类型之间的转换。同时分析了BaseTypeHandler的setParameter()方法和getResult()方法。getNullableResult是一个抽象类,具体方法由其他实现类实现。
