返回顶部
首页 > 资讯 > 后端开发 > Python >Mybatis-plus多数据源配置的两种方式总结
  • 289
分享到

Mybatis-plus多数据源配置的两种方式总结

Mybatis plus多数据源配置方式Mybatis plus多数据源配置 2022-11-13 18:11:29 289人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录1.多数据源配置类1).pom.xml 项目依赖2)多数据源配置类3) 多Mapper4) application.properties 配置文件5) 测试类2.@DS 注解 切

1.多数据源配置类

整体项目结构

1).pom.xml 项目依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="Http://Maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sz</groupId>
    <artifactId>mybatisDataSourcesDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>MybatisDataSourcesDemo</name>
    <description>MybatisDataSourcesDemo</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>Mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.sz.mybatisdatasourcesdemo.MybatisDataSourcesDemoApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <Goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2)多数据源配置类

DataSource -> sqlsessionFactory -> SqlSessionTemplate

​ -> DataSourceTransactionManager

(1).DS1DataSourceConfig 配置类

@MapperScan(basePackages = "com.sz.mybatisdatasourcesdemo.mapper.ds1",sqlSessionTemplateRef = "db1SqlSessionTemplate")
@Component
public class DS1DataSourceConfig {

    @Bean
    // 给DataSource 绑定属性值
    @ConfigurationProperties(prefix = "ds1")
    //创建一个数据源对象 底层通过 BeanUtils.instantiateClass(type); 实例化一个数据源对象
    //候选的数据源有
    //"com.zaxxer.hikari.HikariDataSource",
    //	"org.apache.Tomcat.jdbc.pool.DataSource", "org.apache.commons.dbcp2.BasicDataSource"
    public DataSource ds1DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory ds1SqlsessionFactory (
            @Qualifier("ds1DataSource")DataSource dataSource
    )throws Exception
    {
        // 工厂bean  SqlSessionFactory
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        //设置数据源
        bean.setDataSource(dataSource);
        //加载映射文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:mybatis/ds1/*.xml"));
        return bean.getObject();
    }

    @Bean
    // 数据源事务管理器
    public DataSourceTransactionManager db1TransactionManager(@Qualifier("ds1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("ds1SqlsessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

(2).DS2DataSourceConfig 配置类

@MapperScan(basePackages = "com.sz.mybatisdatasourcesdemo.mapper.ds2",sqlSessionTemplateRef = "ds2SqlSessionTemplate")
@Component
public class DS2DataSourceConfig {

    @Bean
    // 给DataSource 绑定属性值
    @ConfigurationProperties(prefix = "ds2")
    //创建一个数据源对象 底层通过 BeanUtils.instantiateClass(type); 实例化一个数据源对象
    //候选的数据源有
    //"com.zaxxer.hikari.HikariDataSource",
    //	"org.apache.tomcat.jdbc.pool.DataSource", "org.apache.commons.dbcp2.BasicDataSource"
    public DataSource ds2DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory ds2SqlsessionFactory (
            @Qualifier("ds2DataSource")DataSource dataSource
    )throws Exception
    {
        // 工厂bean  SqlSessionFactory
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        //设置数据源
        bean.setDataSource(dataSource);
        //加载映射文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:mybatis/ds2/*.xml"));
        return bean.getObject();
    }

    @Bean
    // 数据源事务管理器
    public DataSourceTransactionManager ds2TransactionManager(@Qualifier("ds2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public SqlSessionTemplate ds2SqlSessionTemplate(@Qualifier("ds2SqlsessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

3) 多Mapper

ds1 路径下 与 ds2 路径下各一个 mapper文件 分别由 ds1配置类 与 ds2配置类 去扫描生成代理类

4) application.properties 配置文件

用两个数据库模拟不同的数据源

# 应用名称
spring.application.name=MybatisDataSourcesDemo

mybatis-plus.mapper-locations=classpath:mybatis/mapper/ds1/*.xml,classpath:mybatis/mapper/ds2/*.xml

#ds1
ds1.type=com.alibaba.druid.pool.DruidDataSource
ds1.jdbc-url=jdbc:mysql://localhost:3306/ds1?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
ds1.username=root
ds1.passWord=root
ds1.driver-class-name=com.mysql.cj.jdbc.Driver

#ds2
ds2.type=com.alibaba.druid.pool.DruidDataSource
ds2.jdbc-url=jdbc:mysql://localhost:3306/ds2?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
ds2.username=root
ds2.password=root
ds2.driver-class-name=com.mysql.cj.jdbc.Driver

5) 测试类

 @Autowired
    private AnimalService animalService;
    @Autowired
    private UserService userService;

    @Test
    void contextLoads() {
        animalService.remove(null);
        userService.remove(null);

        Animal animal = new Animal();
        animal.setName("老虎");
        animalService.save(animal);

        User user = new User();
        user.setName("张三");
        userService.save(user);

        List<Animal> animals = animalService.list();
        System.out.println("animals = " + animals);

        List<User> userList = userService.list();
        System.out.println("userList = " + userList);

    }

2.@DS 注解 切换数据源

分别在 ds1和 ds2库中添加 user 表

1) 新增依赖

版本与 mybatis-plus保存一致

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

2) application.yml 配置类

spring:
  datasource:
    dynamic:
#      primary: master #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        slave_1:
          url: jdbc:mysql://localhost:3306/ds1?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
        slave_2:
          url: jdbc:mysql://localhost:3306/ds2?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver

3) 添加 @DS注解 切换数据源

@Service
public class UserServiceImpl
        extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Override
    @DS("slave_1")
    public List<User> findAllDS1()
    {
        return this.baseMapper.selectList(null);
    }

    @Override
    @DS("slave_2")
    public List<User> findAllDS2()
    {
        return this.baseMapper.selectList(null);
    }
}

4) 测试类

   @Test
    void testDS()
    {
        List<User> allDS1 = userService.findAllDS1();
        System.out.println("allDS1 = " + allDS1);
        List<User> allDS2 = userService.findAllDS2();
        System.out.println("allDS2 = " + allDS2);
    }

到此这篇关于Mybatis-plus多数据源配置的两种方式总结的文章就介绍到这了,更多相关Mybatis-plus多数据源配置内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Mybatis-plus多数据源配置的两种方式总结

本文链接: https://lsjlt.com/news/169341.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作