mybatis plus当月数据查询_Springboot+mybatis(plus)+druid多数据源

前言:

我不太喜欢AOP读自定义注解来切换数据源.因为如果我一个业务里需要同时查2个数据源的数据而又不想把这个业务拆成2个方法的时候,就比较麻烦了.

所以我打算根据package来扫描注入不同的DataSource.可能是我搜索的姿势不太对 , 资料比较少.也会碰到不少坑.所以记录一下.

正文:

mybatis 和 mybatisplus的区别不大 ,一起记了.

springboot 和 mybatis jar就不说了.

druid的jar⬇️

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
  1. 配置数据库连接信息
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      # psi 库
      psi:
        url: jdbc:postgresql://127.0.0.1:5432/psidb
        driver-class-name: org.postgresql.Driver
        username: username
        password: password
      # b2b 库
      b2badapter:
        url: jdbc:mysql://127.0.0.1:13306/b2b?useSSL=false&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8&allowMultiQueries=true
        driver-class-name: com.mysql.jdbc.Driver
        username: username
        password: username

其实就是在spring.datasource.druid下再指定2个连接.

2.有了连接信息, 就去代码配置DataSource的Bean了.

@Configuration
public class DataSourceConfig {
    /**
     * PSI 库连接配置前缀 (与 yml 中的连接信息前缀一致 , 下同)
     */
    private static final String PSI_DATASOURCE_PREFIX = "spring.datasource.druid.psi";
    /**
     * PSI 库连接Bean名字
     */
    public static final String PSI_DATASOURCE_BEAN_NAME = "psiDataSource";
    /**
     * B2B 库中间库连接配置前缀
     */
    private static final String B2B_DATASOURCE_PREFIX = "spring.datasource.druid.b2badapter";
    /**
     * B2B 库中间库连接Bean名字
     */
    public static final String B2B_DATASOURCE_BEAN_NAME = "b2bDataSource";


    @Primary
    @Bean(name = PSI_DATASOURCE_BEAN_NAME)
    @ConfigurationProperties(prefix = PSI_DATASOURCE_PREFIX)
    public DruidDataSource psi() {
        return new DruidDataSource();
    }


    @Bean(name = B2B_DATASOURCE_BEAN_NAME)
    @ConfigurationProperties(prefix = B2B_DATASOURCE_PREFIX)
    public DruidDataSource b2b() {
        return new DruidDataSource();
    }
}

这个@Primary还是有点用, 等下说.

3.配置每个库对应的SqlSessionFactory

以第一个库(psi)举例

@Configuration
@MapperScan(basePackages = "com.a.b.c.d.e.psi.dao", sqlSessionTemplateRef = "psiSqlSessionTemplate")
public class PsiDataSourceConfig {

    @Autowired
    @Qualifier(DataSourceConfig.PSI_DATASOURCE_BEAN_NAME)
    private DataSource psi;

    @Primary
    @Bean("psiSqlSessionFactory")
    public SqlSessionFactory psiSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(psi);

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        factoryBean.setConfiguration(configuration);
        //指定xml路径.
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/a/b/c/d/e/psi/mapper/*Dao.xml"));

        return factoryBean.getObject();
    }


    @Primary
    @Bean("psiSqlSessionTemplate")
    public SqlSessionTemplate psiSqlSessionTemplate() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(psiSqlSessionFactory()); // 使用上面配置的Factory
        return template;
    }
}

算了, 第二个也放上来吧

@Configuration
@MapperScan(basePackages = "com.a.b.c.d.e.b2b.dao", sqlSessionTemplateRef = "b2bSqlSessionTemplate")
public class B2BDataSourceConfig {

    @Autowired
    @Qualifier(DataSourceConfig.B2B_DATASOURCE_BEAN_NAME)
    private DataSource b2b;

    @Bean("b2bSqlSessionFactory")
    public SqlSessionFactory b2bSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(b2b);

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        factoryBean.setConfiguration(configuration);
        //指定xml路径.
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/a/b/c/d/e/b2b/mapper/*Dao.xml"));
        factoryBean.setPlugins(new Interceptor[]{
                new PaginationInterceptor(),
                new PerformanceInterceptor(),
                new OptimisticLockerInterceptor()
        });
        return factoryBean.getObject();
    }

    @Bean("b2bSqlSessionTemplate")
    public SqlSessionTemplate b2bSqlSessionTemplate() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(b2bSqlSessionFactory()); // 使用上面配置的Factory
        return template;
    }
}
这个配置是MybatisPlus的MybatisSqlSessionFactoryBean,通过这个类才能使用MybatisPlus的BaseMapper

如果只是Mybatis的话...

@Bean
public SqlSessionFactory mysqlSqlSessionFactory() throws Exception {
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(b2b);
    //指定xml路径.
    factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/a/b/c/d/e/b2b/mapper/*Dao.xml"));
    return factoryBean.getObject();
}

普通的SqlSessionFactoryBean就行了..

这2个数据源就是通过类上的

@MapperScan(basePackages = "com.a.b.c.d.e.b2b.dao")

来扫描项目不同包下的Mapper文件来注入不同的数据源.

如果,万一,在某些情况下. 2个MapperScan扫描到重复的包怎么办.....谁有@Primary就谁上..

4.最后的最后.去掉springboot/jpa,druid等的自动配置

在启动类上(当然你也可以在yml里去配)加上

@SpringBootApplication(exclude = {
        DruidDataSourceAutoConfigure.class,
        DataSourceAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        JpaRepositoriesAutoConfiguration.class
})
如果是Mybatis的话,.. 只用去掉DataSourceAutoConfiguration.class应该就行了

/..

然后, 没了吧. 就可以用了.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot项目中使用MyBatis Plus和Druid多数据源的步骤如下: 1. 添加依赖 在`pom.xml`文件中添加以下依赖: ```xml <!-- MyBatis Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.1</version> </dependency> <!-- Druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 2. 配置Druid数据源 在`application.yml`中添加Druid数据源的配置: ```yaml spring: datasource: # 主数据druid: url: jdbc:mysql://localhost:3306/main_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # Druid配置 initialSize: 5 minIdle: 5 maxActive: 20 testOnBorrow: false testOnReturn: false testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 validationQuery: SELECT 1 FROM DUAL # 从数据druid2: url: jdbc:mysql://localhost:3306/sub_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # Druid配置 initialSize: 5 minIdle: 5 maxActive: 20 testOnBorrow: false testOnReturn: false testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 validationQuery: SELECT 1 FROM DUAL ``` 3. 配置MyBatis Plus 在`application.yml`中添加MyBatis Plus的配置: ```yaml mybatis-plus: # 主数据源配置 mapper-locations: classpath:mapper/main/*.xml type-aliases-package: com.example.main.entity global-config: db-config: id-type: auto field-strategy: not_empty logic-delete-value: 1 logic-not-delete-value: 0 configuration: map-underscore-to-camel-case: true log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 从数据源配置 multi-datasource: main: mapper-locations: classpath:mapper/main/*.xml type-aliases-package: com.example.main.entity sub: mapper-locations: classpath:mapper/sub/*.xml type-aliases-package: com.example.sub.entity ``` 4. 配置数据源路由 在`com.example.config`包下创建`DynamicDataSourceConfig`类,用于配置数据源路由: ```java @Configuration public class DynamicDataSourceConfig { @Bean @ConfigurationProperties("spring.datasource.druid") public DataSource mainDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean @ConfigurationProperties("spring.datasource.druid2") public DataSource subDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean public DataSource dynamicDataSource() { DynamicDataSource dynamicDataSource = new DynamicDataSource(); Map<Object, Object> dataSourceMap = new HashMap<>(2); dataSourceMap.put("main", mainDataSource()); dataSourceMap.put("sub", subDataSource()); // 将主数据源作为默认数据源 dynamicDataSource.setDefaultTargetDataSource(mainDataSource()); dynamicDataSource.setTargetDataSources(dataSourceMap); return dynamicDataSource; } @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dynamicDataSource()); sqlSessionFactoryBean.setTypeAliasesPackage("com.example.main.entity"); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/main/*.xml")); return sqlSessionFactoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate() throws Exception { return new SqlSessionTemplate(sqlSessionFactory()); } } ``` 5. 配置数据源切换 在`com.example.config`包下创建`DynamicDataSource`类,用于实现数据源切换: ```java public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSource(); } } ``` 在`com.example.config`包下创建`DataSourceContextHolder`类,用于存储当前数据源: ```java public class DataSourceContextHolder { private static final ThreadLocal<String> DATASOURCE_CONTEXT_HOLDER = new ThreadLocal<>(); public static void setDataSource(String dataSource) { DATASOURCE_CONTEXT_HOLDER.set(dataSource); } public static String getDataSource() { return DATASOURCE_CONTEXT_HOLDER.get(); } public static void clearDataSource() { DATASOURCE_CONTEXT_HOLDER.remove(); } } ``` 在`com.example.aop`包下创建`DataSourceAspect`类,用于切换数据源: ```java @Aspect @Component public class DataSourceAspect { @Pointcut("@annotation(com.example.annotation.DataSource)") public void dataSourcePointCut() { } @Before("dataSourcePointCut()") public void before(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); DataSource dataSource = signature.getMethod().getAnnotation(DataSource.class); if (dataSource != null) { String value = dataSource.value(); DataSourceContextHolder.setDataSource(value); } } @After("dataSourcePointCut()") public void after(JoinPoint joinPoint) { DataSourceContextHolder.clearDataSource(); } } ``` 6. 使用多数据源 在需要使用从数据源的方法上加上`@DataSource("sub")`注解,如: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> listUsers() { DataSourceContextHolder.setDataSource("sub"); List<User> users = userMapper.selectList(null); DataSourceContextHolder.clearDataSource(); return users; } } ``` 这样就完成了Spring Boot项目中使用MyBatis Plus和Druid多数据源的配置。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值