SpringBoot下配置Mybatis多数据源

152 阅读4分钟

spring boot 整合mybatis 多数据源

\

1、搭建一个spring boot工程

这个比较简单,我就不具体的写步骤了,把我的pom.xml配置文件发出来给大家看看。

主要是pom.xml文件里面添加了mybatis和druid,mysql依赖。


   

   
	
    
     4.0.0
    

	
    
     com.ai
    
	
    
     demo
    
	
    
     0.0.1-SNAPSHOT
    
	
    
     jar
    

	
    
     demo
    
	
    
     Demo project for Spring Boot
    

	
    
		
     
      org.springframework.boot
     
		
     
      spring-boot-starter-parent
     
		
     
      1.5.2.RELEASE
     
		
      
     
	
    

	
    
		
     
      UTF-8
     
		
     
      UTF-8
     
		
     
      1.8
     
	
    

	
    
		
     
			
      
       org.springframework.boot
      
			
      
       spring-boot-starter-thymeleaf
      
		
     

		
     
		
     
			
      
       org.mybatis.spring.boot
      
			
      
       mybatis-spring-boot-starter
      
			
      
       1.3.0
      
		
     

		
     
		
     
		    
      
       com.github.pagehelper
      
		    
      
       pagehelper-spring-boot-starter
      
		    
      
       1.1.0
      
		
     
		
     
		
     
			
      
       mysql
      
			
      
       mysql-connector-java
      
		
     
		
     
		
     
			
      
       com.alibaba
      
			
      
       druid
      
			
      
       1.0.19
      
		
     

		
     
			
      
       org.springframework.boot
      
			
      
       spring-boot-starter-test
      
			
      
       test
      
		
     

		
     
			
      
       com.alibaba
      
			
      
       fastjson
      
			
      
       1.2.31
      
		
     

		
     
			
      
       org.apache.commons
      
			
      
       commons-lang3
      
			
      
       3.3
      
		
     
		
	
    

	
	
    
		
     
			
      
				
       
        org.springframework.boot
       
			    
       
        spring-boot-maven-plugin
       
			
      
			
      
			
        
                
       
        org.mybatis.generator
         
                
       
        mybatis-generator-maven-plugin
         
                
       
        1.3.5
         
                
        
         
         
          org.mybatis.generator
          
         
          mybatis-generator-core
          
         
          1.3.5
          
         
         
                
        
         
         
          Generate MyBatis Artifacts
          
         
          package
          
          
          
           generate
           
          
         
         
                
        
         
        
         true
         
         
        
         true
         
         
        
          src/main/resources/mybatis-generator/generatorConfig-learn.xml 
         
         
         
         
            
        
		
     
		
     
		
       
            
        
                
       
        src/main/resources
         
            
        
        
       
	
    



   

2、配置数据源配置信息

配置两个数据源的连接url,用户名,密码,连接池的一些配置我是写死在代码里面了,其实最好是配置在文件里面最好,统一配置,修改方便。

下面是我的application.properties文件配置信息,比较简单。

#指定springboot工程启动tomcat使用的端口,默认8080.可以修改
server.port=8080

#jdbc连接配置
## learn 数据源配置
learn.datasource.url=jdbc:mysql://10.1.45.127:3306/learn?useUnicode=true&characterEncoding=utf-8
learn.datasource.username=dev-bj
learn.datasource.password=123456
learn.datasource.driverClassName=com.mysql.jdbc.Driver

## student 数据源配置
student.datasource.url=jdbc:mysql://10.1.45.127:3306/student?useUnicode=true&characterEncoding=utf-8
student.datasource.username=dev-bj
student.datasource.password=123456
student.datasource.driverClassName=com.mysql.jdbc.Driver

#配置数据源的类型,指定使用阿里的德鲁伊工具管理数据库连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#当只有单数据源的时候dao和mapper的映射可以直接通过如下配置指定
#指定bean所在包
#mybatis.type-aliases-package=com.ai.learning.SpringBootTest.model
#指定映射文件
#mybatis.mapperLocations=classpath:mapper/*.xml

3、java代码实现多数据源的bean注入,因为spring boot有自动注入功能,只需要在方法返回前加上@bean注解就能实现自动注入。

多数据源的配置需要注意的是:

注意点一:必须指定主数据源,就是在主数据源的bean注入上加上一个@Primary,表示同一个类的多个对象注入,优先选择有注解@Primary的对象。

注意点二:非主数据源的bean注入上面一定不能加@Primary注解

注意点三:不同数据源的dao和mapper文件最好分开到不同包路径和文件路径下,这样才能单独的配置文件映射,不然会出错。

  比如,我就是主数据源的配置文件都放在dao.learn 和,mapper/learn

    非主数据源的文件放在dao.student和mapper/student

主数据源的java代码如下:

package com.ai.demos.manager;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;



@Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = StudentDataBase.PACKAGE, sqlSessionFactoryRef = "studentSqlSessionFactory")

public class StudentDataBase {

	static final String PACKAGE = "com.ai.demos.dao.student";
	static final String MAPPER_LOCATION = "classpath:mapper/student/*.xml";
	
	@Value("${student.datasource.url}")
    private String url;
 
    @Value("${student.datasource.username}")
    private String user;
 
    @Value("${student.datasource.password}")
    private String password;
 
    @Value("${student.datasource.driverClassName}")
    private String driverClass;
	
    @Bean(name = "studentDataSource", destroyMethod =  "close")
    @Primary
    public DataSource studentDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(user);//用户名
        dataSource.setPassword(password);//密码
        dataSource.setDriverClassName(driverClass);
        dataSource.setInitialSize(2);//初始化时建立物理连接的个数
        dataSource.setMaxActive(20);//最大连接池数量
        dataSource.setMinIdle(0);//最小连接池数量
        dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。
        dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql
        dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
        dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。
        dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache
        return dataSource;
    }
    
    @Bean(name = "studentTransactionManager")
    @Primary
    public DataSourceTransactionManager studentTransactionManager() {
        return new DataSourceTransactionManager(studentDataSource());
    }
	
	@Bean(name = "studentSqlSessionFactory")
    @Primary
    public SqlSessionFactory studentSqlSessionFactory(@Qualifier("studentDataSource") DataSource studentDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(studentDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(StudentDataBase.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

非主数据源的java代码如下:

package com.ai.demos.manager;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;



@Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = StudentDataBase.PACKAGE, sqlSessionFactoryRef = "studentSqlSessionFactory")

//从数据源,不是主数据源,对于bean的注入千万不要使用@Primary,只能主数据库使用,不然报错
public class StudentDataBase {

	//dao层的包路径
	static final String PACKAGE = "com.ai.demos.dao.student";
	//mapper文件的相对路径
	static final String MAPPER_LOCATION = "classpath:mapper/student/*.xml";
	
	@Value("${student.datasource.url}")
    private String url;
 
    @Value("${student.datasource.username}")
    private String user;
 
    @Value("${student.datasource.password}")
    private String password;
 
    @Value("${student.datasource.driverClassName}")
    private String driverClass;
	
    @Bean(name = "studentDataSource", destroyMethod =  "close")
    public DataSource studentDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(user);//用户名
        dataSource.setPassword(password);//密码
        dataSource.setDriverClassName(driverClass);
        dataSource.setInitialSize(2);//初始化时建立物理连接的个数
        dataSource.setMaxActive(20);//最大连接池数量
        dataSource.setMinIdle(0);//最小连接池数量
        dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。
        dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql
        dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
        dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。
        dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache
        return dataSource;
    }
    
    @Bean(name = "studentTransactionManager")
    public DataSourceTransactionManager studentTransactionManager() {
        return new DataSourceTransactionManager(studentDataSource());
    }
	
	@Bean(name = "studentSqlSessionFactory")
    public SqlSessionFactory studentSqlSessionFactory(@Qualifier("studentDataSource") DataSource studentDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(studentDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(StudentDataBase.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

由于我是使用了druid数据库连接池配置,所以可能返回的DateResource对象可能和你不一定一样,你也可以返回简单的DateResource对象。

\

4、对于spring boot工程的dao层代码一定要在类上面手动加上@Mapper注解,不然没法实现自动注入。

\

5、对于service和controller层代码,和正常的springMVC代码一致,没有任何区别。

由于博客没法贴太多代码,我把这个工程的源代码放到了下载资源里面,想参考源代码的同学直接下载即可

百度网盘分享地址如下

链接:pan.baidu.com/s/1jIQfVsa 密码:odz9

csdn下载资源连接如下

download.csdn.net/detail/tian…

github资源地址为:

github.com/jiuquguiyu/…\

\

如果大家使用有什么问题,或者对源代码有什么疑问,可以直接在下面评论,然后一起讨论解决方法。谢谢!

\