SpringBoot、Mybatis、通用Mapper多数据源

背景

随着项目的强化,单一数据源不再满足需求。不同的业务需要操作不同的数据库。本篇采用spring-boot结合mybatis整合多数据源。

maven依赖


	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.1.0.RELEASE
	
	com.jx.aisino
	shzafkpt
	0.0.1-SNAPSHOT
	war

	
		
			org.springframework
			spring-aspects
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.boot
			spring-boot-starter-jdbc
		
		
		
			com.google.guava
			guava
			18.0
		

				
		
		
		    org.apache.hadoop
		    hadoop-client
		    2.6.5
		
		
		
		
		
			com.zaxxer
			HikariCP
		
		
		
		    com.oracle
		    ojdbc14
		    10.2.0.1.0
		

		
			javax.servlet
			servlet-api
			2.5
		

		
		
			com.fasterxml.jackson.core
			jackson-databind
		

		
		
			org.codehaus.jackson
			jackson-mapper-asl
			1.9.1
		
		
		
		
			org.apache.commons
			commons-lang3
		
		
			org.apache.commons
			commons-io
			1.3.2
		
		
			commons-fileupload
			commons-fileupload
			1.3.2
		
		
			commons-codec
			commons-codec
		
		
			commons-lang
			commons-lang
			2.5
		
		
		
		
			com.github.abel533
			mapper
			2.3.0
		
		
		
			org.mybatis
			mybatis
			3.2.8
		
		
			org.mybatis
			mybatis-spring
			1.2.2
		
		
			com.github.jsqlparser
			jsqlparser
			0.9.1
		
		
			com.github.pagehelper
			pagehelper
			3.4.2
		
		
		
			log4j
			log4j
			1.2.17
		
		
			org.slf4j
			slf4j-log4j12
			provided
		
		
		
			com.alibaba
			fastjson
			1.1.41
		
		
	   	
			javax.persistence
			persistence-api
			1.0
		
		
		
			redis.clients
			jedis
		
	
	
		
			
			
				org.apache.maven.plugins
				maven-resources-plugin
				
					UTF-8
				
			
			
			
				org.apache.maven.plugins
				maven-compiler-plugin
				
					1.8
					1.8
					UTF-8
				
			
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

项目结构

SpringBoot、Mybatis、通用Mapper多数据源_第1张图片

配置数据源

package com.aisino.shzafkpt.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@ComponentScan(basePackages = "com.aisino")
@PropertySource(value = {"classpath:jdbc.properties"})
@SpringBootApplication(exclude = {MultipartAutoConfiguration.class})
public class MainApplication extends SpringBootServletInitializer{
	
	@Value("${db.username}")
	private String username;
	@Value("${db.password}")
	private String passwd;
	@Value("${url}")
	private String jdbcUrl;
	
	@Value("${hjwUsername}")
	private String hjwUsername;
	@Value("${hjwPassword}")
	private String hjwPassword;
	@Value("${hjwUrl}")
	private String hjwUrl;
	
	@Value("${nczdryUrl}")
	private String nczdryUrl;
	@Value("${nczdryUsername}")
	private String nczdryUsername;
	@Value("${nczdryPassword}")
	private String nczdryPassword;
	
	@Value("${lgUrl}")
	private String lgUrl;
	@Value("${lgUsername}")
	private String lgUsername;
	@Value("${lgPassword}")
	private String lgPassword;
		
	@Value("${driver}")
	private String driverClassName;
	@Value("${maxPoolSize}")
	private Integer maxPoolSize;
	@Value("${minIdle}")
	private Integer minIdle;
	@Value("${validationTimeout}")
	private Integer validationTimeout;
	@Value("${idleTimeout}")
	private Integer idleTimeout;
	
	@Bean(destroyMethod = "close",name = "dataSource")
	@Primary
    public DataSource dataSource() throws Exception {
		HikariConfig configuration = new HikariConfig();
    	configuration.setJdbcUrl(jdbcUrl);
    	configuration.setDriverClassName(driverClassName);
    	configuration.setMaximumPoolSize(maxPoolSize);
    	configuration.setMinimumIdle(minIdle);
    	configuration.setValidationTimeout(validationTimeout);
    	configuration.setIdleTimeout(idleTimeout);
    	configuration.setConnectionTestQuery("select count(1) from tab_kh");
    	configuration.setUsername(username);
    	configuration.setPassword(passwd);
		HikariDataSource dataSource = new HikariDataSource(configuration);
        return dataSource;
    }
	
	@Bean(destroyMethod = "close",name = "hjwDataSource")
	public DataSource dataSource4Lg() throws Exception {
		HikariConfig configuration = new HikariConfig();
		configuration.setJdbcUrl(hjwUrl);
		configuration.setDriverClassName(driverClassName);
		configuration.setMaximumPoolSize(maxPoolSize);
		configuration.setMinimumIdle(minIdle);
		configuration.setValidationTimeout(validationTimeout);
		configuration.setIdleTimeout(idleTimeout);
		configuration.setConnectionTestQuery("select 1+1 from dual");
		configuration.setUsername(hjwUsername);
		configuration.setPassword(hjwPassword);
		HikariDataSource dataSource = new HikariDataSource(configuration);
		return dataSource;
	}
	
	@Bean(destroyMethod = "close",name = "nczdryDataSource")
	public DataSource dataSource4Nczdry() throws Exception {
		HikariConfig configuration = new HikariConfig();
		configuration.setJdbcUrl(nczdryUrl);
		configuration.setDriverClassName(driverClassName);
		configuration.setMaximumPoolSize(maxPoolSize);
		configuration.setMinimumIdle(minIdle);
		configuration.setValidationTimeout(validationTimeout);
		configuration.setIdleTimeout(idleTimeout);
		configuration.setConnectionTestQuery("select 1+1 from dual");
		configuration.setUsername(nczdryUsername);
		configuration.setPassword(nczdryPassword);
		HikariDataSource dataSource = new HikariDataSource(configuration);
		return dataSource;
	}
	
	@Bean(destroyMethod = "close",name = "nclgDataSource")
	public DataSource dataSource4Nclg() throws Exception {
		HikariConfig configuration = new HikariConfig();
		configuration.setJdbcUrl(lgUrl);
		configuration.setDriverClassName(driverClassName);
		configuration.setMaximumPoolSize(maxPoolSize);
		configuration.setMinimumIdle(minIdle);
		configuration.setValidationTimeout(validationTimeout);
		configuration.setIdleTimeout(idleTimeout);
		configuration.setConnectionTestQuery("select 1+1 from dual");
		configuration.setUsername(lgUsername);
		configuration.setPassword(lgPassword);
		HikariDataSource dataSource = new HikariDataSource(configuration);
		return dataSource;
	}

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(MainApplication.class);
    }
    
    public static void main(String[] args) {
    	SpringApplication.run(MainApplication.class, args);
	}

}

数据源1整合mybstis

package com.aisino.shzafkpt.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
@MapperScan(basePackages = "com.aisino.shzafkpt.mapper.trunk",sqlSessionTemplateRef = "defaultSqlSessionTemplate")
public class MyBatisConfig {

    @Autowired
    @Qualifier(value = "dataSource")
    private DataSource dataSource;
  
    @Bean(name = "defaultSqlSessionFactoryBean")
    @Primary
    public SqlSessionFactory defaultSqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = null;
		try {
			sqlSessionFactoryBean = new SqlSessionFactoryBean();
			// 设置数据源
			sqlSessionFactoryBean.setDataSource(dataSource);
			// 设置mybatis的主配置文件
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/mybatis-config.xml");
			sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
			// 设置别名包
			sqlSessionFactoryBean.setTypeAliasesPackage("com.aisino.shzafkpt.bean");
			// 配置mapper的扫描,找到所有的mapper.xml映射文件
			Resource[] resources = resolver.getResources("classpath:mybatis/mappers/*.xml");
			sqlSessionFactoryBean.setMapperLocations(resources);
		} catch (Exception e) {
			e.printStackTrace();
		}

        return sqlSessionFactoryBean.getObject();
    }
    
    @Bean("defaultSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate defaultSqlSessionTemplate() throws Exception{
		SqlSessionTemplate template = new SqlSessionTemplate(defaultSqlSessionFactoryBean());
		return template;
    }
}

数据源2整合mybatis

package com.aisino.shzafkpt.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
@MapperScan(basePackages = "com.aisino.shzafkpt.mapper.hjw",sqlSessionTemplateRef = "hjwSqlSessionTemplate")
public class HjwMyBatisConfig {

    @Autowired
    @Qualifier(value = "hjwDataSource")
    private DataSource hjwDataSource;
    
    @Bean(name = "hjwSqlSessionFactoryBean")
    public SqlSessionFactory hjwSqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = null;
		try {
			sqlSessionFactoryBean = new SqlSessionFactoryBean();
			// 设置数据源
			sqlSessionFactoryBean.setDataSource(hjwDataSource);
			// 设置mybatis的主配置文件
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/mybatis-config.xml");
			sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);
			// 设置别名包
			sqlSessionFactoryBean.setTypeAliasesPackage("com.aisino.shzafkpt.model");
			// 配置mapper的扫描,找到所有的mapper.xml映射文件
			Resource[] resources = resolver.getResources("classpath:mybatis/hjws/*.xml");
			sqlSessionFactoryBean.setMapperLocations(resources);
		} catch (Exception e) {
			e.printStackTrace();
		}

        return sqlSessionFactoryBean.getObject();
    }
    
    @Bean("hjwSqlSessionTemplate")
    public SqlSessionTemplate defaultSqlSessionTemplate() throws Exception{
		SqlSessionTemplate template = new SqlSessionTemplate(hjwSqlSessionFactoryBean());
		return template;
    }
}

注意修改mapper所在包及xml文件存放位置
SpringBoot、Mybatis、通用Mapper多数据源_第2张图片

通用Mapper

package com.aisino.shzafkpt.config;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@AutoConfigureAfter(MyBatisConfig.class) 
public class MapperScannerConfig {
    
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.aisino.shzafkpt.mapper");
        return mapperScannerConfigurer;
    }

}

你可能感兴趣的:(java)