SpringBoot之优雅的多数据源(MybatisPlus)

背景:

项目需要将sqlserver2000的数据处理后转存到mysql数据库(解决:1、不能调用mybatisplus默认方法;2、加密数据库密码的问题)

1、添加依赖

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.0.25</version>
</dependency>
<!-- 数据库-->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>com.microsoft</groupId>
	<artifactId>sqljdbc4</artifactId>
	<version>3.0</version>
</dependency>
<dependency>
	<groupId>com.microsoft.sqlserver</groupId>
	<artifactId>mssql-jdbc</artifactId>
	<version>6.2.0.jre8</version>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatisplus-spring-boot-starter</artifactId>
	<version>1.0.5</version>
</dependency>
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus</artifactId>
	<version>2.1.9</version>
</dependency>
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<!-- 默认的版本为3.8.1,修改为4.x,因为3.x使用的为编程的方式,4.x为注解的形式。 -->
	<version>4.12</version>
</dependency>
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<scope>provided</scope>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-test</artifactId>
	<version>4.3.14.BUILD-SNAPSHOT</version>
</dependency>
		

2、application.properties配置

#数据库连接配置
#db1(默认)
spring.datasource.db1.url=jdbc:mysql://localhost:3306/data_platform?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
spring.datasource.db1.username=root
spring.datasource.db1.password=root
spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver
#db2
spring.datasource.db2.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.db2.url=jdbc:sqlserver://127.0.0.1;databaseName=ICXFDB;
spring.datasource.db2.username=sa
spring.datasource.db2.password=root

3、自定义@Configuration配置(数据库1)

//表示这个类为一个配置类
@Configuration
// 配置mybatis的接口类放的地方
@MapperScan(basePackages = {"atage.platform.mapper.db1"}, sqlSessionFactoryRef = "test1SqlSessionFactory")
@EnableTransactionManagement
public class DataSourceConfig1 {
	// 将这个对象放入Spring容器中
	@Bean(name = "test1DataSource")
	// 表示这个数据源是默认数据源
	@Primary
	// 读取application.properties中的配置参数映射成为一个对象
	// prefix表示参数的前缀
	@ConfigurationProperties(prefix = "spring.datasource.db1")
	public DataSource getDateSource1() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "test1SqlSessionFactory")
	// 表示这个数据源是默认数据源
	@Primary
	// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
	public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource datasource)
			throws Exception {
//		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();//不能调用mybatisplus默认方法
		MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();//能调用mybatisplus默认方法
        bean.setPlugins(new Interceptor[]{
                new PaginationInterceptor(),//分页插件
                new PerformanceInterceptor(),//性能分析器
                new OptimisticLockerInterceptor(),//乐观锁
        });
		bean.setDataSource(datasource);
		bean.setMapperLocations(
				// 设置mybatis的xml所在位置
				new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/db1/*.xml"));
		return bean.getObject();
	}

	@Bean("test1SqlSessionTemplate")
	// 表示这个数据源是默认数据源
	@Primary
	public SqlSessionTemplate test1sqlsessiontemplate(
			@Qualifier("test1SqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
	}
}

4、自定义@Configuration配置(数据库2)

@Configuration
@MapperScan(basePackages = "atage.platform.mapper.db2", sqlSessionFactoryRef = "test2SqlSessionFactory")
@EnableTransactionManagement
public class DataSourceConfig2 {

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

	@Bean(name = "test2SqlSessionFactory")
	public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource datasource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setPlugins(new Interceptor[]{
				new PaginationInterceptor(),//分页插件
				new PerformanceInterceptor(),//性能分析器
				new OptimisticLockerInterceptor(),//乐观锁
		});
		bean.setDataSource(datasource);
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/db2/*.xml"));
		return bean.getObject();
	}

	@Bean("test2SqlSessionTemplate")
	public SqlSessionTemplate test2sqlsessiontemplate(
			@Qualifier("test2SqlSessionFactory") SqlSessionFactory sessionfactory) {
		return new SqlSessionTemplate(sessionfactory);
	}
}

5、接下来就是写接口测试了(包括单元测试、Service层、Mapper层和xml)
在这里插入图片描述

6、介绍

第三、四步初始化数据库连接,映射db1和db2下的(mapper接口和mybatis下的xml);
db1、db2共用同一个service,通过service调用不同mapper(mapper对应不同数据库)
这个是我在测试期间碰到的问题:
//SqlSessionFactoryBean bean = new SqlSessionFactoryBean();//不能调用mybatisplus默认方法
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();//能调用mybatisplus默认方法
如果想在初始化数据库连接时,自定义用户名密码等,重写DriverManagerDataSource

重写DriverManagerDataSource(涉及到连接加密时)
在这里插入图片描述

7、测试

每层的代码不用贴出吧,都一样
自己写一个单元测试

	@Test
    public synchronized void test02() {
    	//获取云数据库中最新数据时间
        String xfsj1 = lssjService.getXfsj1ByYunDB();
        //如果没有,则取60天前时间
        if(StringUtils.isEmpty(xfsj1)) xfsj1 = DateUtils.getFixedDateTime(-60);
        //获取当前时间
        String xfsj2 = DateUtils.formatTimesTampDate(new Date());
        //获取sqlserver数据库数据
        List<Lssj> lssjList = lssjService.getLssjListByXfsj(xfsj1,xfsj2);
        if(!lssjList.isEmpty()){
        	//保存到云数据库
            lssjService.save(lssjList);
        }
    }
原创文章 139 获赞 401 访问量 50万+

猜你喜欢

转载自blog.csdn.net/qq_31122833/article/details/105252893