SoFunction
Updated on 2025-03-03

SpringCloud integrated MybatisPlus to implement MySQL multi-data source configuration method

Introduce dependencies

<dependency>
    <groupId></groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>druid</artifactId>
    <version>1.1.15</version>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Configure multiple data sources

Configure multiple data sources in:

-class-name=
=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
=root
=root
-class-name=
=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
=root
=root
=
-size=10
-size=20
-size=5
-wait=30000
=stat,wall,log4j
-enabled=true
-prefix=
=true
-pattern=/druid/*
=true
=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
-total=20
-idle=10
-idle=5
-between-eviction-runs-millis=60000
-evictable-idle-time-millis=300000
-query=SELECT 1 FROM dual
-on-borrow=true
-on-return=true
-while-idle=true
-abandoned=true
-abandoned-timeout=60000
-abandoned=true

Configuration explanation

This is a property file in a Spring Boot application that configures database connections. Here is an explanation of each configuration project:

  • -class-name: Specifies the JDBC driver class name of the main database, here is the driver class of the MySQL database.
  • : The JDBC URL of the main database specifies the location and connection parameters of the database, including character encoding, time zone, etc.
  • : The user name of the primary database.
  • : Password of the primary database.
  • -class-name: Specifies the JDBC driver class name from the database (copy), which is also the driver class of the MySQL database.
  • : From the JDBC URL of the database, different places from the primary database may include different database names or connection parameters.
  • : Username from the database.
  • : Password from the database.
  • : Data source type, Alibaba's Druid data source is used here.
  • -size: The initial connection pool size of the data source, indicating the number of database connections that will be created at startup.
  • -size: The maximum connection pool size of the data source, indicating the maximum number of connections allowed in the connection pool.
  • -size: The minimum connection pool size of the data source, indicating the minimum number of connections allowed in the connection pool.
  • -wait: Gets the maximum waiting time (milliseconds) when connecting. If all connections in the connection pool are occupied and the maximum number of connections is reached, the new request will wait for a while.
  • : A filter for data source, which can be used for monitoring, security and other purposes. This includes statistics (stat), SQL firewall (wall) and log (log4j).
  • -enabled: Whether to enable Druid's connection pool log.
  • -prefix: Prefix for connection pool logs.
  • : Whether to enable Druid's statistics viewing servlet.
  • -pattern: Statistics view the URL path of the servlet.
  • : Whether to enable Druid's web statistics filter.
  • : The resource paths that need to be excluded, such as JavaScript, pictures, etc.
  • -total: The maximum number of active connections, the same as -size.
  • -idle: Maximum number of idle connections.
  • -idle: Minimum number of idle connections.
  • -between-eviction-runs-millis: The connection pool periodically checks the interval of free connections.
  • -evictable-idle-time-millis: The minimum idle time for a connection in the connection pool, and connections beyond this time will be recycled.
  • -query: SQL query to verify that the connection is valid.
  • -on-borrow: Whether to test the validity of a connection when borrowing it.
  • -on-return: Whether to test the validity of the connection when returning it.
  • -while-idle: Whether to test the validity of the connection when the connection is idle.
  • -abandoned: Whether to remove connections that have not been used for a long time.
  • -abandoned-timeout: Sets the timeout time for a long time without using the connection.
  • -abandoned: Whether to log the log of the connection that was removed.
  • These configuration items are used to define settings such as connection pools between the application and the database, database connection properties, and connection pool monitoring. Different configuration items can be adjusted according to the needs of the application.

Configure MybatisPlus

Configure MybatisPlus in:

-locations=classpath:mapper/*.xml
-type=auto
-delete-value=1
-not-delete-value=0
-namespace=test
-namespace=

Configuring MybatisPlus Explanation

This is a configuration file for MyBatis Plus (usually referred to as MyBatis+ or MP) to configure the behavior of MyBatis Plus in Spring Boot applications. Here is an explanation of each configuration project:

  • -locations=classpath:mapper/*.xml: This configuration item specifies the location of the Mapper XML file of MyBatis Plus. In this example, it tells MyBatis Plus to find all files ending in ".xml" in the "mapper" directory under the classpath to serve as Mapper definition files.
  • -type=auto: This configuration item specifies the generation policy for the primary key ID. Here, setting to "auto" means the primary key value automatically generated using the database, which is usually a self-growth or unique identifier managed by the database.
  • -delete-value=1: This configuration item specifies the logical delete value. In MyBatis Plus, logical deletion is a way to indicate the deletion status by marking records. Set to "1" here to indicate that it has been deleted.
  • -not-delete-value=0: This configuration item specifies a logically undeleted value. In MyBatis Plus, this refers to the status of the record not being deleted. Set to "0" here means that it is not deleted.
  • -namespace=test: This configuration item specifies the basic Mapper namespace. This namespace will be used to generate a fully qualified name of the Mapper interface, usually associated with the package name.
  • -namespace=: This configuration item specifies the namespace of the Mapper interface. In MyBatis Plus, the Mapper interface is associated with an XML file. This configuration item will set the XML file namespace in the generated Mapper interface.
  • These configuration items are used to customize the behavior of MyBatis Plus, including primary key generation policies, logically deleted values, Mapper interface namespace, etc. They allow the behavior of MyBatis Plus to be configured and controlled according to the needs of the application.

Configure Mapper

Create a Mapper interface, such as UserMapper:

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

Using multiple data sources

Where multiple data sources are needed, use the @MapperScan annotation to specify the package path where the Mapper is located:

@SpringBootApplication
@EnableDiscoveryClient
public class Application {
    public static void main(String[] args) {
        (, args);
    }
    @MapperScan("")
    public class MyApp {
        // ...
    }
}

CRUD Example

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User save(User user) {
        return (user);
    }
    @Override
    public User update(User user) {
        return (user);
    }
    @Override
    public User findById(Long id) {
        return (id);
    }
    @Override
    public void delete(Long id) {
        (id);
    }
}
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping
    public User save(@RequestBody User user) {
        return (user);
    }
    @PutMapping("/{id}")
    public User update(@PathVariable Long id, @RequestBody User user) {
        (id);
        return (user);
    }
    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        return (id);
    }
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        (id);
    }
}

Using different data sources

To use different data source queries, you can use the @MapperScan annotation in the Mapper interface to specify the data source you want to use, for example:

@MapperScan("")
public interface UserMapperMaster extends BaseMapper<User> {
}
@MapperScan("")
public interface UserMapperSlave extends BaseMapper<User> {
}

Then, where you need to use different data sources, use the @Autowired annotation to inject the corresponding Mapper interface, for example:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapperMaster userMapperMaster;
    @Autowired
    private UserMapperSlave userMapperSlave;
    @Override
    public User save(User user) {
        return (user);
    }
    @Override
    public User update(User user) {
        return (user);
    }
    @Override
    public User findById(Long id) {
        return (id);
    }
    @Override
    public void delete(Long id) {
        (id);
    }
}

To use a different data source on a method, you can use the @MapperScan annotation on that method to specify the data source you need to use, for example:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapperMaster userMapperMaster;
    @Autowired
    private UserMapperSlave userMapperSlave;
    @Override
    public User save(User user) {
        return (user);
    }
    @Override
    public User update(User user) {
        return (user);
    }
    @Override
    public User findById(Long id) {
        return (id);
    }
    @Override
    public void delete(Long id) {
        (id);
    }
    @MapperScan("")
    @Override
    public User findByIdSlave(Long id) {
        return (id);
    }
}

This is the article about SpringCloud integrating MybatisPlus to implement MySQL multi-data source configuration. For more related SpringCloud MybatisPlus MySQL multi-data source content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!