天天看点

springboot+mybatis踩坑记录

踩坑记录

项目为支持枚举直接映射成数据库字段,定义了

@MappedTypes({EnumA.class})
@MappedJdbcTypes(JdbcType.CHAR)
public class EnumTypeHandler <E extends Enum<E>> extends BaseTypeHandler<E> {
//代码细节
}
           

springboot在启动的时候会在类中TypeHandlerRegistry先去注册所有系统默认的handler,也会将我们定义的handler加载进去。

在idea中运行的时候,很顺利。能将自定义的数据库字段转换成预期的枚举。

然而打包成jar运行后,居然提示No typehandler found for property xxx

首先定位到异常抛出到点

ResultMapping中的validate方法,idea打断点的时候看typeHandler是有值的,但是打成jar包之后,返回却是空的。

猜测,是不是注册的时候出问题了。

SqlSessionFactoryBean定位到hasLength(this.typeHandlersPackage)这一行,typeHandlersPackage这个属性以配置过。

进到register方法

springboot+mybatis踩坑记录

idea断点看到到handlerSet有自定义到class被加载。

jar包打印出来到日志,handlerSet居然是空的。

看下resolverUtil.find()方法。

springboot+mybatis踩坑记录

上面因为VFS没指定,所以用的是默认的DefaultVFS.

从jar中打印的日志看出children为空,进入list,再进入list

springboot+mybatis踩坑记录
springboot+mybatis踩坑记录
springboot+mybatis踩坑记录
springboot+mybatis踩坑记录

在这里,jar中发现line为空,而idea中能正常读到类到class名称。

是不是springboot对使用版本对mybatis不兼容问题?

SpringBoot有自己的mybatis/starter,然后先将mybatis包换掉

org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.0

然后在代码中指定自己的SpringBootVFS

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setVfs(SpringBootVFS.class);
           

附上mybatis官方git问题说明

https://github.com/mybatis/mybatis-3/issues/325

继续阅读