前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Mybatis配置多数据源

Mybatis配置多数据源

作者头像
写一点笔记
发布2022-08-11 17:32:45
5780
发布2022-08-11 17:32:45
举报
文章被收录于专栏:程序员备忘录程序员备忘录

在项目中经常会存在操作不同数据库得情况,最为典型就是后管系统,如果不走接口进行调用,那么势必会有多个数据源作为数据管理的得突破口。在此我们可以想一下到底是微服务接口暴露模式的后管好还是基于多数据源的模式好?虽然都是管理数据,而且效果都差不多。但是接口模式的管理对开发不太友好。所以这块我们稍微学习一下mybatis的多数据配置,我们想要的结果是项目兼容任意多个数据库,这里我们用mysql做为研究对象。至于其他的数据库也是一样的。

在之前我们学习mybatis的时候说mybatis是java的orm框架,然后这个orm框架要和spring进行整合,需要mybatis-spring这样一个桥的东西。当然在springboot中提供了基于自动配置的mybatis,这块我们学的是原生的.

首先我们导入相关的maven依赖

代码语言:javascript
复制
<!--        数据库-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

<!--        orm-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

<!--        orm spring-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

<!--        数据源-->
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.9</version>
        </dependency>

数据源这块采用druid,这块为了实践,我们采用MapperFactoryBean和MapperScannerConfigurer两种方式进行探讨。代码如下:

代码语言:javascript
复制
@Configuration
public class MybatisConfig {

    public DruidDataSource getDruidDataSource(String url,String userName,String password) throws SQLException {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        try {
            ds.setFilters("stat,mergeStat,slf4j");
        } catch (Exception var18) {
        }
        ds.setMaxActive(50);
        ds.setInitialSize(1);
        ds.setMinIdle(1);
        ds.setMaxWait(60000);
        ds.setTimeBetweenEvictionRunsMillis(120000);
        ds.setMinEvictableIdleTimeMillis(300000);
        ds.setValidationQuery("SELECT 'x'");
        ds.setPoolPreparedStatements(true);
        ds.setMaxPoolPreparedStatementPerConnectionSize(30);
        ds.setTestWhileIdle(true);
        ds.setTestOnReturn(false);
        ds.setTestOnBorrow(false);
        ds.init();
        return ds;
    }

    @Bean(name = "dataO")
    public SqlSessionFactoryBean getSqlSessionFactoryOne1() throws Exception {
        //xml和实体的映射
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(getDruidDataSource("jdbc:mysql://127.0.0.1:3306/tianjl?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true","root","tianjingle"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.example.demo.one");
        Resource[] resources = new Resource[]{new ClassPathResource("tian/one/OneMapper.xml")};
        sqlSessionFactoryBean.setMapperLocations(resources);
        return sqlSessionFactoryBean;
    }

    @Bean(name = "dataTwo")
    public MapperFactoryBean getSqlSessionFactoryTwo() throws Exception {
        //xml和实体的映射
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(getDruidDataSource("jdbc:mysql://127.0.0.1:3306/tianjl?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true","root","tianjingle"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.example.demo.two");
        sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("tian/two/TwoMapper.xml"));
        //单个数据源所有的数据库映射
        MapperFactoryBean mapperFactoryBean=new MapperFactoryBean();
        //设置sqlSessionTemplate,zhuru yong de
        mapperFactoryBean.setMapperInterface(TwoMapper.class);
        mapperFactoryBean.setSqlSessionFactory(sqlSessionFactoryBean.getObject());
        return mapperFactoryBean;
    }

    @Bean
    @ConditionalOnBean(name = "dataO")
    public static MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer=new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.example.demo.one.mapper");
//这块指定扫描的接口
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("dataO");
        return mapperScannerConfigurer;
    }
}

在完成上述方法之后,我们编写测试方法

代码语言:javascript
复制
    @Resource
    private OneMapper oneMapper;


    @Resource
    private TwoMapper twoMapper;


    @GetMapping(value = "/one")
    public BaikeResponse one(){
        BaikeResponse baikeResponse=new BaikeResponse();
        baikeResponse.setData(oneMapper.one());
        return baikeResponse;
    }

    @GetMapping(value = "/two")
    public BaikeResponse two(){
        BaikeResponse baikeResponse=new BaikeResponse();
        baikeResponse.setData(twoMapper.two());
        return baikeResponse;
}

小结:这块我们采用比较原始的方式配置了了两种多数据源的实现,这块我们也可以对此进行扩展,封装成让习惯了使用starter的同学摸不着头脑的形式。好了,本次demo就演示到这里了。

晚安~

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-08-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 写点笔记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档