飞道的博客

Spring Boot 整合 MyBatis Plus实现多数据源的两种方式

301人阅读  评论(0)

第一种:使用配置类的方式:

项目结构

        

 xml依赖:


  
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>multi-datasource-parent </artifactId>
  7. <groupId>com.ganbo </groupId>
  8. <version>1.0-SNAPSHOT </version>
  9. </parent>
  10. <modelVersion>4.0.0 </modelVersion>
  11. <artifactId>multi-datasource-config </artifactId>
  12. <properties>
  13. <maven.compiler.source>8 </maven.compiler.source>
  14. <maven.compiler.target>8 </maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework.boot </groupId>
  19. <artifactId>spring-boot-starter-web </artifactId>
  20. </dependency>
  21. <!-- mybatis-plus -->
  22. <dependency>
  23. <groupId>com.baomidou </groupId>
  24. <artifactId>mybatis-plus-boot-starter </artifactId>
  25. <version>3.3.1 </version>
  26. </dependency>
  27. <!-- mybatis-plus代码生成器 -->
  28. <dependency>
  29. <groupId>com.baomidou </groupId>
  30. <artifactId>mybatis-plus-generator </artifactId>
  31. <version>3.3.1.tmp </version>
  32. </dependency>
  33. <!-- mysql连接 -->
  34. <dependency>
  35. <groupId>mysql </groupId>
  36. <artifactId>mysql-connector-java </artifactId>
  37. <scope>runtime </scope>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.springframework.boot </groupId>
  41. <artifactId>spring-boot-starter-test </artifactId>
  42. <scope>test </scope>
  43. </dependency>
  44. <dependency>
  45. <groupId>org.projectlombok </groupId>
  46. <artifactId>lombok </artifactId>
  47. <optional>true </optional>
  48. </dependency>
  49. </dependencies>
  50. <build>
  51. <plugins>
  52. <plugin>
  53. <groupId>org.springframework.boot </groupId>
  54. <artifactId>spring-boot-maven-plugin </artifactId>
  55. </plugin>
  56. </plugins>
  57. </build>
  58. </project>

多数据源配置类(DataSource -> SqlsessionFactory -> SqlSessionTemplate -> DataSourceTransactionManager)

DataSourceUserConfig 配置类:


  
  1. package com.multidb.configdemo.config;
  2. import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
  3. import org.apache.ibatis.session.SqlSessionFactory;
  4. import org.mybatis.spring.SqlSessionTemplate;
  5. import org.mybatis.spring.annotation.MapperScan;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.boot.context.properties.ConfigurationProperties;
  8. import org.springframework.boot.jdbc.DataSourceBuilder;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.context.annotation.Primary;
  12. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  13. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  14. import javax.sql.DataSource;
  15. @Configuration
  16. @MapperScan(basePackages = "com.multidb.configdemo.dao.user", sqlSessionTemplateRef = "userSqlSessionTemplate")
  17. public class DataSourceUserConfig {
  18. @Primary //设置主数据源
  19. @Bean(name = "userDataSource")
  20. @ConfigurationProperties(prefix = "spring.datasource.user")
  21. public DataSource userDataSource () {
  22. return DataSourceBuilder.create().build();
  23. }
  24. @Bean(name = "userSqlSessionFactory")
  25. public SqlSessionFactory userSqlSessionFactory (@Qualifier("userDataSource") DataSource dataSource) throws Exception {
  26. //工厂bean SqlSessionFactory
  27. MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
  28. //设置数据源
  29. bean.setDataSource(dataSource);
  30. //加载映射文件
  31. bean.setMapperLocations( new PathMatchingResourcePatternResolver().
  32. getResources( "classpath*:mapper/user/*.xml"));
  33. return bean.getObject();
  34. }
  35. // 数据源事务管理器
  36. public DataSourceTransactionManager db1TransactionManager (@Qualifier("userDataSource") DataSource dataSource) {
  37. return new DataSourceTransactionManager(dataSource);
  38. }
  39. @Bean(name = "userSqlSessionTemplate")
  40. public SqlSessionTemplate userSqlSessionTemplate (@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  41. return new SqlSessionTemplate(sqlSessionFactory);
  42. }
  43. }

DataSourceOrderConfig 配置类:


  
  1. package com.multidb.configdemo.config;
  2. import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
  3. import org.apache.ibatis.session.SqlSessionFactory;
  4. import org.mybatis.spring.SqlSessionTemplate;
  5. import org.mybatis.spring.annotation.MapperScan;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.boot.context.properties.ConfigurationProperties;
  8. import org.springframework.boot.jdbc.DataSourceBuilder;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  12. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  13. import javax.sql.DataSource;
  14. @Configuration
  15. @MapperScan(basePackages = "com.multidb.configdemo.dao.order", sqlSessionTemplateRef = "orderSqlSessionTemplate")
  16. public class DataSourceOrderConfig {
  17. // @Primary
  18. @Bean(name = "orderDataSource")
  19. @ConfigurationProperties(prefix = "spring.datasource.order")
  20. public DataSource orderDataSource () {
  21. return DataSourceBuilder.create().build();
  22. }
  23. @Bean(name = "orderSqlSessionFactory")
  24. public SqlSessionFactory orderSqlSessionFactory (@Qualifier("orderDataSource") DataSource dataSource) throws Exception {
  25. //工厂bean SqlSessionFactory
  26. MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
  27. //设置数据源
  28. bean.setDataSource(dataSource);
  29. //加载映射文件
  30. bean.setMapperLocations( new PathMatchingResourcePatternResolver().
  31. getResources( "classpath*:mapper/order/*.xml"));
  32. return bean.getObject();
  33. }
  34. // 数据源事务管理器
  35. public DataSourceTransactionManager db1TransactionManager (@Qualifier("orderDataSource") DataSource dataSource) {
  36. return new DataSourceTransactionManager(dataSource);
  37. }
  38. @Bean(name = "orderSqlSessionTemplate")
  39. public SqlSessionTemplate orderSqlSessionTemplate (@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  40. return new SqlSessionTemplate(sqlSessionFactory);
  41. }
  42. }

多个mapper接口:

  application.properties 配置文件


  
  1. spring:
  2. datasource:
  3. user:
  4. driver-class-name: com.mysql.cj.jdbc.Driver
  5. username: root
  6. password: root
  7. jdbc-url: jdbc:mysql: //127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
  8. order:
  9. driver-class-name: com.mysql.cj.jdbc.Driver
  10. username: root
  11. password: root
  12. jdbc-url: jdbc:mysql: //127.0.0.1:3306/order?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
  13. mybatis-plus:
  14. # mapper-locations: classpath:mapper /*.xml # xml文件路径
  15. configuration:
  16. map-underscore-to-camel-case: true # 驼峰转换
  17. cache-enabled: false # 是否开启缓存
  18. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印sql
  19. # global-config: # 全局配置
  20. # db-column-underline: true # 数据库字段驼峰下划线转换
  21. # id-type: 0 # id自增类型(数据库id自增)

第二种:使用@DS 注解 切换数据源

新增pom依赖:


  
  1. <!-- Mybatis plus多数据源支持,版本与 mybatis-plus保存一致 -->
  2. <dependency>
  3. <groupId>com.baomidou </groupId>
  4. <artifactId>dynamic-datasource-spring-boot-starter </artifactId>
  5. <version>3.3.1 </version>
  6. </dependency>

application.yml 配置


  
  1. spring:
  2. datasource:
  3. dynamic:
  4. primary: user #设置默认的数据源或者数据源组,默认值即为master
  5. strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
  6. datasource:
  7. user:
  8. url: jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
  9. username: root
  10. password: root
  11. driver-class-name: com.mysql.jdbc.Driver #3.2.0开始支持SPI可省略此配置
  12. order:
  13. url: jdbc:mysql://127.0.0.1:3306/order?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
  14. username: root
  15. password: root
  16. driver-class-name: com.mysql.jdbc.Driver
  17. mybatis-plus:
  18. mapper-locations: classpath:mapper/**/*.xml #xml文件路径
  19. configuration:
  20. map-underscore-to-camel-case: true #驼峰转换
  21. cache-enabled: false #是否开启缓存
  22. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql
  23. # global-config: #全局配置
  24. # db-column-underline: true #数据库字段驼峰下划线转换
  25. # id-type: 0 #id自增类型(数据库id自增)

添加 @DS注解 切换数据源


  
  1. import com.baomidou.dynamic.datasource.annotation.DS;
  2. import com.multidb.annotationdemo.dao.order.OrderDao;
  3. import com.multidb.annotationdemo.entity.order.Order;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. @Service
  7. @DS("order")
  8. public class OrderService {
  9. @Autowired
  10. OrderDao orderDao;
  11. public Order getOrder () {
  12. return orderDao.selectByPrimaryKey( 1L);
  13. }
  14. }

  
  1. package com.multidb.annotationdemo.service;
  2. import com.baomidou.dynamic.datasource.annotation.DS;
  3. import com.multidb.annotationdemo.dao.user.UserDao;
  4. import com.multidb.annotationdemo.entity.user.User;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. @Service
  8. @DS("user")
  9. public class UserService {
  10. @Autowired
  11. UserDao userDao;
  12. public User getUser () {
  13. return userDao.selectByPrimaryKey( 1L);
  14. }
  15. }

启动类配置扫描mapper接口:


  
  1. @SpringBootApplication
  2. @MapperScan("com.multidb.annotationdemo.dao.**")
  3. public class Datasource1Application {
  4. public static void main (String[] args) {
  5. SpringApplication.run(Datasource1Application.class, args);
  6. }
  7. }

测试


  
  1. @RestController
  2. public class IndexController {
  3. @Autowired
  4. UserService userService;
  5. @Autowired
  6. OrderService orderService;
  7. @GetMapping("/getUser")
  8. public User getUser () {
  9. return userService.getUser();
  10. }
  11. @GetMapping("/getOrder")
  12. public Order getOrder () {
  13. return orderService.getOrder();
  14. }
  15. }

项目源码以及数据库脚本: multi-datasource-parent: Spring boot 整合 MyBatis 实现多数据源。


转载:https://blog.csdn.net/u010972055/article/details/127930188
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场