ZBLOG

message : "Cannot invoke \"com.baomidou.mybatisplus.core.mapper.BaseMapper.selectById(java.io.Serializable)\" because the return value of \"com.baomidou.mybatisplus.extension.service.IService.getBaseMapper()\" is null"

这个错误表明在使用 MyBatis-Plus 时,尝试调用 getBaseMapper().selectById() 方法时出现了空指针异常(NPE)。具体原因是 getBaseMapper() 返回了 null。以下是可能的原因和解决方案:


常见原因及修复方法

1. Service 实现类未正确继承 ServiceImpl

  • 问题:自定义的 ServiceImpl 类没有继承 MyBatis-Plus 的 ServiceImpl<M, T>
  • 修复
    1. @Service
    2. public class YourServiceImpl extends ServiceImpl<YourMapper, YourEntity> implements YourService {
    3. // 你的代码
    4. }
    确保:
    • YourMapper 是继承 BaseMapper<T> 的 Mapper 接口。
    • YourEntity 是对应的实体类。

2. Mapper 接口未扫描或未注入

  • 问题:MyBatis-Plus 未扫描到 Mapper 接口,导致 Spring 容器中不存在该 Bean。
  • 修复
    • 在启动类上添加 @MapperScan
      1. @SpringBootApplication
      2. @MapperScan("com.your.package.mapper") // 指定 Mapper 接口所在的包
      3. public class Application { ... }
    • 在 Mapper 接口上直接加 @Mapper
      1. @Mapper
      2. public interface YourMapper extends BaseMapper<YourEntity> { ... }

####3. MyBatis-Plus配置问题

  • 问题:配置文件中缺少 MyBatis-Plus 相关配置。
  • 修复:检查 application.yml/application.properties
    1. mybatis-plus:
    2. mapper-locations: classpath*:/mapper/**/*.xml # XML映射文件路径(如果有)
    3. configuration:
    4. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #可选:开启SQL日志

####4. 依赖冲突或版本不兼容

  • 问题:项目中可能存在 MyBatis/MyBatis-Plus/JDBC等依赖版本冲突。
  • 修复: 1.检查依赖树(Maven/Gradle)是否有冲突:
    1. mvn dependency:tree | grep mybatis
    2.确保使用兼容版本(例如 MyBatis-Plus ≥3.5.x + Spring Boot ≥2.7.x)。

调试步骤

  1. 检查 ServiceImpl 继承关系:确认是否漏掉 extends ServiceImpl<M, T>
  2. 查看 Spring Bean:在启动时检查日志中是否有 Mapper/Service Bean加载成功的记录。
  3. 单元测试验证:单独测试 yourService.getBaseMapper()是否为 null。

如果仍有问题,可以提供更多上下文代码(如Service/Mapper定义),我会进一步帮你分析!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23420

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?