SqlSessionFactory多数据源配置案例(springBoot)

1、项目目录图示:

2、案例依赖:

<parent>
    <artifactId>spring-boot-parent</artifactId>
    <groupId>org.springframework.boot</groupId>
    <version>2.2.12.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <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>
    </dependency>

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

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.2.14</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

3、案例配置文件yml:

server:
  port: 8099

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    db1:
      jdbc-url: jdbc:mysql://localhost:3306/db1?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=true
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver

    db2:
      jdbc-url: jdbc:mysql://localhost:3306/db2?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=true
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver

    druid: # druid数据库连接池的基本初始化属性
      initial-size: 5 # 连接池初始化的大小
      min-idle: 1 # 最小空闲的线程数
      max-active: 20 # 最大活动的线程数


mybatis-plus:
  mapper-locations: classpath:/mapper/*/*.xml # 配置MyBatis-Plus扫描Mapper文件的位置
  type-aliases-package: com.hua.bean # 创建别名的类所在的包
  configuration:
    map-underscore-to-camel-case: true # 开启驼峰命名

#sql语句打印
logging:
  level:
    #路径
    com.hua: debug

4、重点 ,SqlSessionFactory的配置如下:(MySQLDataSourceConfig1类

@Configuration
@MapperScan(basePackages = "com.hua.mapper.db1", sqlSessionFactoryRef = "MySQLSqlSessionFactory1")
public class MySQLDataSourceConfig1 {

    @Bean(name = "MySQLDataSource1")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource getDateSource1() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "MySQLSqlSessionFactory1")
    @Primary
    public SqlSessionFactory test1SqlSessionFactory(
            @Qualifier("MySQLDataSource1") DataSource datasource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean ();
        bean.setDataSource(datasource);
        bean.setMapperLocations(// 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db1/*.xml"));
        return bean.getObject();
    }


    @Bean("MySQLSqlSessionTemplate1")
    @Primary
    public SqlSessionTemplate test1SqlSessionTemplate(
            @Qualifier("MySQLSqlSessionFactory1") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

    @Bean
    public PlatformTransactionManager transactionManager1(@Qualifier("MySQLDataSource1")DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}

4.5、第二个(多个数据源则多个这种配置类) ,SqlSessionFactory的配置如下:(MySQLDataSourceConfig2类 

@Configuration
@MapperScan(basePackages = "com.hua.mapper.db2", sqlSessionFactoryRef = "MySQLSqlSessionFactory2")
public class MySQLDataSourceConfig2 {

    @Bean(name = "MySQLDataSource2")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource getDateSource2() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "MySQLSqlSessionFactory2")
    public SqlSessionFactory test2SqlSessionFactory(
            @Qualifier("MySQLDataSource2") DataSource datasource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean ();
        bean.setDataSource(datasource);
        bean.setMapperLocations(// 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db2/*.xml"));
        return bean.getObject();
    }


    @Bean("MySQLSqlSessionTemplate2")
    public SqlSessionTemplate test2SqlSessionTemplate(
            @Qualifier("MySQLSqlSessionFactory2") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

//    此处根据数据库的类型来配置,在MySQLDataSourceConfig1类中已经配置了mysql的事务类型,如此处数据库类型也是mysql则不用配置,否则将注释放开正常配置即可
//    @Bean
//    public PlatformTransactionManager transactionManager2(@Qualifier("MySQLDataSource2")DataSource dataSource) {
//        return new DataSourceTransactionManager(dataSource);
//    }

}

 相同的数据库类型PlatformTransactionManager事务管理器只需配置一次加入ioc即可不用重复配置,不同数据库类型则需要再次配置bean加入容器(放开上面代码注释即可)。

补充:启动类上加入注解取消datasource的自动配置

 

5、测试代码:

 

 注解方式Spring Boot配置多数据源操作参考:

注解方式Spring Boot配置多数据源操作_O_G的博客-CSDN博客

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
【资源说明】 1、基于springboot+mybatis实现的外卖订餐系统源码+项目说明(毕设).zip 2、该资源包括项目的全部源码,下载可以直接使用! 3、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习借鉴。 4、本资源作为“参考资料”如果需要实现其他功能,需要能看懂代码,并且热爱钻研,自行调试。 ### 项目概述 首先来了解项目需求。 项目分为客户端和后台管理系统两个界面,客户端针对普通用户,功能包括用户登陆、用户退出、菜品订购、我的订单。 后台管理系统针对管理员,功能包括管理员登陆、管理员退出、添加菜品、查询菜品、修改菜品、删除菜品、订单处理、添加用户、查询用户、删除用户。 需求了解完之后,接下来设计系统,首先分配出4个服务提供者,account、menu、order、user。 - account - 提供账户服务:用户和管理员登陆。 - menu - 提供菜品服务:添加菜品、查询菜品、修改菜品、删除菜品。 - order - 提供订单服务:添加订单、查询订单、删除订单、处理订单。 - user - 提供用户服务:添加用户、查询用户、删除用户、用户修改。 ## 异常 - org.springframework.beans.factory.UnsatisfiedDependencyException 不满足依赖异常 - org.springframework.beans.factory.BeanCreationException - org.springframework.beans.BeanInstantiationException - org.springframework.core.NestedIOException - org.apache.ibatis.builder.BuilderException - java.lang.IllegalArgumentException ``` Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [C:\Users\GUSHI\IdeaProjects\springboot2\target\classes\mapping\UserRepository.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. Cause: java.lang.IllegalArgumentException: Mapped Statements collection already contains value for com.m.dao.AdminDao.login at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireByType (AbstractAutowireCapableBeanFactory.java:1431)
在Spring Boot中配置MyBatis多数据源可以通过以下步骤进行: 1. 添加相关依赖:导入MyBatis和数据库驱动的依赖,例如MySQL或者其他数据库的驱动。 2. 配置数据源:在`application.properties`或`application.yml`中配置多个数据源的连接信息,例如: ```yaml spring: datasource: primary: url: jdbc:mysql://localhost:3306/primary_db username: primary_user password: primary_password secondary: url: jdbc:mysql://localhost:3306/secondary_db username: secondary_user password: secondary_password ``` 这里配置了两个数据源,一个是主数据源(primary),另一个是次要数据源(secondary)。 3. 配置数据源 Bean:创建多个数据源的`DataSource`对象,并将其注册为Spring Bean。可以使用`@Configuration`注解的类来完成这个配置,例如: ```java @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } } ``` 这里通过`@ConfigurationProperties`注解将数据源的配置信息绑定到对应的`DataSource`对象。 4. 配置MyBatis SqlSessionFactory:创建多个SqlSessionFactory对象,分别关联不同的数据源。可以使用`@MapperScan`注解扫描MyBatis的Mapper接口,并指定对应的SqlSessionFactory对象,例如: ```java @Configuration @MapperScan(basePackages = "com.example.primary", sqlSessionFactoryRef = "primarySqlSessionFactory") public class MyBatisConfigPrimary { @Bean public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource) throws Exception { SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); sessionFactoryBean.setDataSource(primaryDataSource); return sessionFactoryBean.getObject(); } } @Configuration @MapperScan(basePackages = "com.example.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory") public class MyBatisConfigSecondary { @Bean public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) throws Exception { SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); sessionFactoryBean.setDataSource(secondaryDataSource); return sessionFactoryBean.getObject(); } } ``` 这里通过`@MapperScan`注解指定了不同包下的Mapper接口,并关联了对应的SqlSessionFactory对象。 5. 配置事务管理器(可选):如果需要使用事务管理,可以配置多个事务管理器,并指定对应的数据源。例如: ```java @Configuration @EnableTransactionManagement public class TransactionConfig { @Autowired @Qualifier("primaryDataSource") private DataSource primaryDataSource; @Autowired @Qualifier("secondaryDataSource") private DataSource secondaryDataSource; @Bean public DataSourceTransactionManager primaryTransactionManager() { return new DataSourceTransactionManager(primaryDataSource); } @Bean public DataSourceTransactionManager secondaryTransactionManager() { return new DataSourceTransactionManager(secondaryDataSource); } } ``` 这里通过`@EnableTransactionManagement`启用事务管理,同时配置了对应的数据源的事务管理器。 通过以上配置,即可实现MyBatis多数据源配置。注意,在编写Mapper接口时,需要通过`@Qualifier`注解指定使用哪个数据源。例如: ```java @Qualifier("primarySqlSessionFactory") @Repository public interface PrimaryMapper { // ... } @Qualifier("secondarySqlSessionFactory") @Repository public interface SecondaryMapper { // ... } ``` 这样就可以在不同的Mapper接口中使用不同的数据源了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值