mybatis在预处理语句(PreparedStatement)中设置一个参数时,或者从结果集(ResultSet)中取出一个值时,都会用到TypeHandler。
作用:
就是将java类型(javaType)转化为jdbc类型(jdbcType),或者将jdbc类型(jdbcType)转化为java类型(javaType)。
启用
启用该TypeHandler 可以有以下几种方式:
在Spring Boot的配置文件增加type-handlers-package的配置
type-handlers-package的配置的值为TypeHandler的包名即可,即在application.properties文件增加以下配置:
mybatis.type-handlers-package=com.xxx.typehandler
该配置会被org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration读取,并调用org.mybatis.spring.SqlSessionFactoryBean来完成TypeHandler的初始化。
在Spring Boot指定MyBatisConfig文件的路径,之后在MyBatisConfig中配置typeHandlers
配置如下: - 在application.properties文件增加以下配置:
mybatis.config-location=classpath:mybatis-config.xml
在mybatis-config.xml文件增加以下配置:
<configuration>
<typeHandlers>
<package name="com.xxx.typehandler"/>
</typeHandlers>
</configuration>
注:如果在application.properties文件指定了mybatis.configuration ,又同时配置mybatis.config-location,则需要把application.properties的mybatis.configuration的配置移到mybatis-config.xml文件里。否则启用会校验失败。
- 也可以直接在mybatis-config.xml配置指定的typeHandler类
<configuration>
<typeHandlers>
<typeHandler handler="com.xxx.typehandler.MyStringTypehandler"/>
</typeHandlers>
</configuration>
注:无法在application.properties文件直接配置typeHandler类,因为虽然org.mybatis.spring.SqlSessionFactoryBean有setTypeHandlers(TypeHandler<?>[] typeHandlers)方法,但org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration并没有去application.properties读取相关的配置并设置调用该方法。
网友评论