天天看点

SpringBoot升级Mybatis为MybatisPlus遇到的问题及解决前言最初尝试运行错误的尝试正确的解决方法

前言

​ MP的安装使用正如他官网说的异常简单,但是在原有的Mybatis项目兼容Mybatis-Plus还是遇到了些许问题:MyBatisPlus的整合(springboot)和使用。

先说结论

  1. ​ 检测依赖是否正确引入;
  2. ​ 检测使用的BaseMapper是否正确的依赖;
  3. ​ 检查POJO对应表名称,字段名称是否对应,若表存在主键,需要指定POJO中对应主键(用注解 @TableId 注解表 ID 主键);
  4. ​ 检查是否被扫描到Dao:@MapperScan;
  5. ​ application.properties配置是否恰当;

最终我的问题是:

mybatis.mapper-locations

mybatis-plus.mapper-locations

导致的。这里我只记录这个过程,1、2、3、4点已在基础博客中有写到:

最初尝试运行

#mybatis相关配置文件
mybatis.mapper-locations=classpath*:mapper/*Dao.xml
#mybatis-plus.mapper-locations=classpath*:mapper/*Dao.xml
           

出现了问题,进行了错误的尝试。

错误的尝试

刚开始测试用的是baseMapper里面的selectList方法,未用到自行编写的映射mapper.xml文件;误以为需要将 mybatis 的 sqlSessionFactoryBean给替换:

添加appliication.properties配置:

mybatis-plus.global-config.sql-session-factory=com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean
           

报错:

SpringBoot升级Mybatis为MybatisPlus遇到的问题及解决前言最初尝试运行错误的尝试正确的解决方法
SpringBoot升级Mybatis为MybatisPlus遇到的问题及解决前言最初尝试运行错误的尝试正确的解决方法

终归原因还是配置赋值是String,而要求是SqlSessonFactory。

正确的解决方法

分别给mybatis和mp指定映射文件对象:

值得注意的是如果

mybatis

mybatis-plus

两个都写了就要保持一致,如下,如果一个写了,另外一个没写,则会报对应的配置找不到:

#mybatis相关配置文件
mybatis.mapper-locations=classpath*:mapper/*Dao.xml
mybatis-plus.mapper-locations=classpath*:mapper/*Dao.xml
           

单独只配置

mybatis

,则无法支持mp:

报错:

Unsatisfied dependency expressed through bean property ‘sqlSessionFactory’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sqlSessionFactory’ defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method ‘sqlSessionFactory’ threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: ‘xx’ \target\classes\mapper\config\sqlMapConfig.xml]’. Cause: java.lang.NullPointerException’

单独将

mybatis.mapper-locations

mybatis.config-location

替换为对应的mp,则无法兼容原有的

mybatis

代码;

SpringBoot升级Mybatis为MybatisPlus遇到的问题及解决前言最初尝试运行错误的尝试正确的解决方法

最后添加:

#mybatis相关配置文件
mybatis.mapper-locations=classpath*:mapper/*Dao.xml
mybatis.config-location=classpath:mapper/config/sqlMapConfig.xml
mybatis-plus.mapper-locations=classpath*:mapper/*Dao.xml
mybatis-plus.config-location=classpath:mapper/config/sqlMapConfig.xml
           

继续阅读