栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot升级Mybatis为MybatisPlus遇到的问题及解决

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

报错:

终归原因还是配置赋值是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’ targetclassesmapperconfigsqlMapConfig.xml]’. Cause: java.lang.NullPointerException’


单独将mybatis.mapper-locations和mybatis.config-location替换为对应的mp,则无法兼容原有的mybatis代码;

最后添加:

#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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/345149.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号