【Spring技术专题】「实战开发系列」保姆级教你SpringBoot整合Mybatis框架实现多数据源的静态数据源和动态数据源配置落地

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: Mybatis是一个基于JDBC实现的,支持普通 SQL 查询、存储过程和高级映射的优秀持久层框架,去掉了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索封装。Mybatis主要思想是将程序中大量的 SQL 语句剥离出来,配置在配置文件中,以实现 SQL 的灵活配置。在所有 ORM 框架中都有一个非常重要的媒介——PO(持久化对象),PO 的作用就是完成持久化操作,通过该对象对数据库执行增删改的操作,以面向对象的方式操作数据库。

Mybatis是什么

Mybatis是一个基于JDBC实现的,支持普通 SQL 查询、存储过程和高级映射的优秀持久层框架,去掉了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索封装。

Mybatis主要思想是将程序中大量的 SQL 语句剥离出来,配置在配置文件中,以实现 SQL 的灵活配置。在所有 ORM 框架中都有一个非常重要的媒介——PO(持久化对象),PO 的作用就是完成持久化操作,通过该对象对数据库执行增删改的操作,以面向对象的方式操作数据库。

SpringBoot整合Mybatis框架实现多数据源操作

当我们使用SpringBoot整合Mybatis时,我们通常会遇到多数据源的问题。在这种情况下,我们需要使用动态数据源来处理多个数据源。本文将介绍如何使用SpringBoot整合Mybatis的多数据源和动态数据源。

应用场景

项目需要同时连接两个不同的数据库A, B,并且它们都为主从架构,一台写库,多台读库。

选择和配置Maven依赖

使用SpringBoot整合Mybatis需要添加Maven起步依赖,如下所示。

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>x.x.x</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>x.x.xx</version>
</dependency>

这些依赖将帮助我们整合Mybatis和Druid数据源。

禁掉DataSourceAutoConfiguration

首先,要将spring boot自带的DataSourceAutoConfiguration禁掉,因为它会读取application.properties文件的spring.datasource.* 属性并自动配置单数据源。

去除DataSourceAutoConfiguration

在@SpringBootApplication注解中添加exclude属性即可。

@SpringBootApplication(exclude = {
   
   DataSourceAutoConfiguration.class})
public class WebApplication {
   
   
    public static void main(String[] args) {
   
   
        SpringApplication.run(WebApplication.class, args);
    }
}

定制化配置对应的数据源

由于我们禁掉了自动数据源配置,因些下一步就需要手动将这些数据源创建出来。

配置主、从数据源

当接下来,我们需要配置数据源时,我们需要在application.properties文件中创建多个数据源的配置块。为了区分不同的数据源,我们可以使用spring.datasource.druid.* 前缀。

以下是一个示例,我们定义了两个数据源:主数据源和从数据源,并且我们使用Druid数据源来管理它们。在application.properties中的配置如下所示:

主数据源

spring.datasource.druid.master.url=jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.druid.master.username=root
spring.datasource.druid.master.password=root
spring.datasource.druid.master.driver-class-name=com.mysql.jdbc.Driver

从数据源

spring.datasource.druid.slave.url=jdbc:mysql://localhost:3306/slave?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.druid.slave.username=root
spring.datasource.druid.slave.password=root
spring.datasource.druid.slave.driver-class-name=com.mysql.jdbc.Driver

通过以上配置,我们成功地定义了两个数据源,并使用了Druid数据源来管理它们。这样的配置可以确保应用程序能够顺利地访问并管理多个数据源。

配置Mybatis和定义主从数据源对象

接下来,我们需要配置Mybatis。我们需要为每个数据源创建一个SqlSessionFactory。以下是一个示例:

@Configuration
@MapperScan(basePackages = "com.xx.xxx.mapper")
public class DynamicDataSourceConfiguration {
   
   

    @Bean(name = "masterDataSource")
    // application.properteis中对应属性的前缀
    @ConfigurationProperties(prefix = "spring.datasource.druid.master")
    public DataSource masterDataSource() {
   
   
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "slaveDataSource")
    // application.properteis中对应属性的前缀
    @ConfigurationProperties(prefix = "spring.datasource.druid.slave")
    public DataSource slaveDataSource() {
   
   
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
                                         @Qualifier("slaveDataSource") DataSource slaveDataSource) {
   
   
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER, masterDataSource);
        targetDataSources.put(DataSourceType.SLAVE, slaveDataSource);
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
        return dynamicDataSource;
    }
}

方案1:MapperScan配置扫描

在启动类中添加对mapper包扫描 @MapperScan

@SpringBootApplication
@MapperScan("com.xxx.xxx.xxx")

在这个示例中,我们创建了两个SqlSessionFactory:masterSqlSessionFactory和slaveSqlSessionFactory。我们还创建了一个动态数据源,它可以根据需要切换到不同的数据源。我们使用@Qualifier注释来指定每个数据源的名称。

方案1:手动编程配置对应的SessionFactory
    // 需要为每个数据源创建一个SqlSessionFactory。以下是一个示例:
    @Bean(name = "masterSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception {
   
   
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(masterDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/master/*.xml"));
        return bean.getObject();
    }

    // 需要为每个数据源创建一个SqlSessionFactory。以下是一个示例:
    @Bean(name = "slaveSqlSessionFactory")
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource slaveDataSource) throws Exception {
   
   
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(slaveDataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/slave/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "sqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("dynamicDataSource") DataSource dynamicDataSource) throws Exception {
   
   
        return new SqlSessionTemplate(dynamicDataSource);
    }

添加了上面的配置注解之后,会进行扫描所有的Mybatis的Mapper接口类,进行注入到对应的Spring的上下文中。此外还有另外一种方式就只通过@MapperScan的sqlSessionFactoryRef方式指定对应的SessionFactory并且定义扫描方式。

方案2:注解编程配置对应的SessionFactory

接下来需要配置两个mybatis的SqlSessionFactory分别使用不同的数据源:

@Configuration
@MapperScan(basePackages = {
   
   "com.xxxx.mapper"}, sqlSessionFactoryRef = "masterSqlSessionFactory")
    public class MasterSqlSessionFactoryConfiguration {
   
   
        @Autowired
        @Qualifier("masterDataSource")
        private DataSource masterDataSource;
        @Bean
        public SqlSessionFactory sqlSessionFactory1() throws Exception {
   
   
               SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(masterDataSource); 
            return factoryBean.getObject();
       }
       @Bean
       public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
   
   
           SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); 
          // 使用上面配置的Factory
          return template;
      }
 }

经过上面的配置后,com.xxxx.mapper下的Mapper接口,都会使用master数据源。同理可配第二个SqlSessionFactory:

@Configuration
@MapperScan(basePackages = {
   
   "com.xxxx.dao"}, sqlSessionFactoryRef = "slaveSqlSessionFactory")
    public class SlaveSqlSessionFactoryConfiguration {
   
   
        @Autowired
        @Qualifier("slaveDataSource")
        private DataSource slaveDataSource;
        @Bean
        public SqlSessionFactory sqlSessionFactory2() throws Exception {
   
   
               SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
            factoryBean.setDataSource(slaveDataSource); 
            return factoryBean.getObject();
       }
       @Bean
       public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
   
   
           SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2()); 
          // 使用上面配置的Factory
          return template;
      }
 }

完成这些配置后,假设有2个Mapper:com.xxxx.mapper.XXXMapper和com.xxxx.dao.Mapper,使用前者时会自动连接master库,后者连接slave库。

创建静态数据源

接下来,我们要针对于多数据源和及动态数据源进行实现对应的落地方案,希望可以帮助到大家,动态数据源: 通过AOP在不同数据源之间动态切换。

    /**
     * @return
     */
    @Bean(name = "dynamicDataSource")
    public DataSource dataSource() {
   
   
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(dataSource1());
        // 配置多数据源
        Map<Object, Object> dsMap = new HashMap(5);
        dsMap.put("masterDataSource", dataSource1());
        dsMap.put("slaveDataSource", dataSource2());
        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }

动态数据源实现处理

使用动态数据源的初衷,是能在应用层做到读写分离,即在程序代码中控制不同的查询方法去连接不同的库。除了这种方法以外,数据库中间件也是个不错的选择,它的优点是数据库集群对应用来说只暴露为单库,不需要切换数据源的代码逻辑。

定义数据源切换上下文

首先定义一个ContextHolder, 用于保存当前线程使用的数据源名:

public class DataSourceContextHolder {
   
   
    /**
     * 默认数据源
     */
    public static final String DEFAULT_DS = "masterDataSource";
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
    // 设置数据源名
    public static void setDB(String dbType) {
   
   
        contextHolder.set(dbType);
    }

    // 获取数据源名
    public static String getDB() {
   
   
        return (contextHolder.get());
    }

    // 清除数据源名
    public static void clearDB() {
   
   
        contextHolder.remove();
    }
}
定义动态切换数据源

我们需要创建一个动态数据源来管理多个数据源,自定义一个javax.sql.DataSource接口的实现,这里只需要继承Spring为我们预先实现好的父类AbstractRoutingDataSource即可。

public class DynamicDataSource extends AbstractRoutingDataSource {
   
   
    @Override
    protected Object determineCurrentLookupKey() {
   
   
        return DataSourceContextHolder.getDB();
    }
}

在这个示例中,我们使用DataSourceContextHolder来获取当前线程的数据源类型。DataSourceContextHolder是一个自定义的类,它使用ThreadLocal来存储当前线程的数据源类型。

AOP的方式实现数据源动态切换

通过自定义注解@DS用于在编码时指定方法使用哪个数据源。

@Retention(RetentionPolicy.RUNTIME)
@Target({
   
    ElementType.METHOD })
public @interface DS {
   
   
    String value() default "masterDataSource";
}
AOP切面实现运行切换机制

编写AOP切面,实现切换数据源逻辑,我们需要在运行时切换数据源。

@Aspect
@Component
public class DynamicDataSourceAspect {
   
   
    @Before("@annotation(DS)")
    public void beforeSwitchDS(JoinPoint point){
   
   
        //获得当前访问的class
        Class<?> className = point.getTarget().getClass();
        //获得访问的方法名
        String methodName = point.getSignature().getName();
        //得到方法的参数的类型
        Class[] argClass = ((MethodSignature)point.getSignature()).getParameterTypes();
        String dataSource = DataSourceContextHolder.DEFAULT_DS;
        try {
   
   
            // 得到访问的方法对象
            Method method = className.getMethod(methodName, argClass);
            // 判断是否存在@DS注解
            if (method.isAnnotationPresent(DS.class)) {
   
   
                DS annotation = method.getAnnotation(DS.class);
                // 取出注解中的数据源名
                dataSource = annotation.value();
            }
        } catch (Exception e) {
   
   
            e.printStackTrace();
        }
        // 切换数据源
        DataSourceContextHolder.setDB(dataSource);
    }
    @After("@annotation(DS)")
    public void afterSwitchDS(JoinPoint point){
   
   
        DataSourceContextHolder.clearDB();
    }
}

完成上述配置后,在先前SqlSessionFactory配置中指定使用DynamicDataSource就可以在Service中愉快的切换数据源了。

@Autowired
    private CXXMapper userAMapper;
    @DS("masterDataSource")
    public String ds1() {
   
   
        return userAMapper.selectByPrimaryKey(1).getName();
    }
    @DS("slaveDataSource")
    public String ds2() {
   
   
        return userAMapper.selectByPrimaryKey(1).getName();
    }
手动编程实现运行切换机制

我们使用DataSourceContextHolder来设置当前线程的数据源类型。在getAllUsers方法中,我们使用主数据源。在getUserById方法中,我们使用从数据源。

@Service
public class UserServiceImpl implements UserService {
   
   

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAllUsers() {
   
   
        DataSourceContextHolder.setDataSourceType(DataSourceType.MASTER);
        return userMapper.getAllUsers();
    }

    @Override
    public User getUserById(int id) {
   
   
        DataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE);
        return userMapper.getUserById(id);
    }
}

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
2月前
|
Oracle 关系型数据库 Java
【YashanDB知识库】Mybatis-Plus适配崖山配置
【YashanDB知识库】Mybatis-Plus适配崖山配置
|
2月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
83 0
|
2月前
|
Java 数据库连接 微服务
微服务——MyBatis配置——事务管理
本段内容主要介绍了事务管理的两种类型:JDBC 和 MANAGED。JDBC 类型直接利用数据源连接管理事务,依赖提交和回滚机制;而 MANAGED 类型则由容器全程管理事务生命周期,例如 JEE 应用服务器上下文,默认会关闭连接,但可根据需要设置 `closeConnection` 属性为 false 阻止关闭行为。此外,提到在使用 Spring + MyBatis 时,无需额外配置事务管理器,因为 Spring 模块自带的功能可覆盖上述配置,且这两种事务管理器类型均无需设置属性。
56 0
|
2月前
|
Java 数据库连接 数据库
微服务——MyBatis配置——多环境配置
在 MyBatis 中,多环境配置允许为不同数据库创建多个 SqlSessionFactory。通过传递环境参数给 SqlSessionFactoryBuilder,可指定使用哪种环境;若忽略,则加载默认环境。`environments` 元素定义环境配置,包括默认环境 ID、事务管理器和数据源类型等。每个环境需唯一标识,确保默认环境匹配其中之一。代码示例展示了如何构建工厂及配置 XML 结构。
51 0
|
2月前
|
缓存 Java 数据库连接
微服务——MyBatis配置——常见配置
本文介绍了 MyBatis 的常见配置及其加载顺序。属性配置优先级为:方法参数传递的属性 &gt; resource/url 属性中配置 &gt; properties 元素中指定属性。同时列举了多个关键配置项,如 `cacheEnabled`(全局缓存开关)、`lazyLoadingEnabled`(延迟加载)、`useGeneratedKeys`(使用 JDBC 自动生成主键)等,并详细说明其作用、有效值及默认值。这些配置帮助开发者优化 MyBatis 的性能与行为。
40 0
|
2月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
59 0
|
2月前
|
Java 数据库连接 数据库
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——MyBatis 介绍和配置
本文介绍了Spring Boot集成MyBatis的方法,重点讲解基于注解的方式。首先简述MyBatis作为持久层框架的特点,接着说明集成时的依赖导入,包括`mybatis-spring-boot-starter`和MySQL连接器。随后详细展示了`properties.yml`配置文件的内容,涵盖数据库连接、驼峰命名规范及Mapper文件路径等关键设置,帮助开发者快速上手Spring Boot与MyBatis的整合开发。
140 0
|
4月前
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
180 2
|
7月前
|
Java 数据库连接 Maven
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和MyBatis Generator,使用逆向工程来自动生成Java代码,包括实体类、Mapper文件和Example文件,以提高开发效率。
299 2
mybatis使用一:springboot整合mybatis、mybatis generator,使用逆向工程生成java代码。
|
7月前
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
196 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块