[Solved] Mybatis Error: CannotFindDataSourceException: dynamic-datasource can not find primary datasource

Problem background

When using mybatis, an error is reported that the master data source cannot be found:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: com.baomidou.dynamic.datasource.exception.CannotFindDataSourceException: dynamic-datasource can not find primary datasource
### The error may exist in com/lanran/transactional/dao/PaymentMapper.java (best guess)
### The error may involve com.lanran.transactional.dao.PaymentMapper.insertBatchSomeColumn
### The error occurred while executing an update
### Cause: com.baomidou.dynamic.datasource.exception.CannotFindDataSourceException: dynamic-datasource can not find primary datasource

Solution

1. Because the multi-source configuration dependency of mybatisplus is added, but the configuration file does not write the related configuration of multi-source, an error is reported

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.5.0</version>
        </dependency>

Method 1: if you don’t use multi-source configuration, remove this dependency
Method 2:  application set multi-source configuration

server:
  port: 40001

spring:
  datasource:
    druid:
      stat-view-servlet:
        enabled: true
    dynamic:
      # Configure the global druid parameter, please configure as needed
      druid:
        initial-size: 5
        max-active: 8
        min-idle: 3
        max-wait: 1000
        validation-query: 'select 1'
      datasource:
        master:
          username: root
          password: 123456
          url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
          driver-class-name: com.mysql.cj.jdbc.Driver
        slave_1:
          username: root
          password: 123456
          url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
          driver-class-name: com.mysql.cj.jdbc.Driver

Read More: