SpringBoot下配置Mybatis多数据源

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代码一致,没有任何区别。

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

百度网盘分享地址如下

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

csdn下载资源连接如下

http://download.csdn.net/detail/tianhouquan/9881563

github资源地址为:

https://github.com/jiuquguiyu/demos


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


  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中整合Mybatis配置JNDI数据源的方法如下: 1. 在application.properties或application.yml文件中,配置JNDI数据源的相关信息。例如,可以使用以下配置: ``` spring.datasource.jndi-name=jndi/oscardb ``` 2. 在Mybatis配置文件中,指定Mapper文件的位置。例如,可以使用以下配置: ``` mybatis.mapper-locations=classpath:mapper/*.xml ``` 3. 在Spring Boot的启动类中,添加`@MapperScan`注解来扫描Mapper接口。例如,可以使用以下配置: ``` @SpringBootApplication @MapperScan("com.example.mapper") public class Application { public static void main(String\[\] args) { SpringApplication.run(Application.class, args); } } ``` 4. 在Spring Boot的配置类中,使用`@Bean`注解配置JNDI数据源。例如,可以使用以下配置: ``` @Configuration public class DataSourceConfig { @Bean public DataSource dataSource() throws NamingException { JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean(); jndiObjectFactoryBean.setJndiName("java:comp/env/jdbc/数据库名"); jndiObjectFactoryBean.afterPropertiesSet(); return (DataSource) jndiObjectFactoryBean.getObject(); } } ``` 通过以上步骤,你可以在Spring Boot中成功配置JNDI数据源并整合Mybatis。 #### 引用[.reference_title] - *1* [springboot + mybatis + jndi](https://blog.csdn.net/jiandong06/article/details/108659673)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [SpringBoot整合MybatisPlus多数据源](https://blog.csdn.net/qq_37284798/article/details/129279732)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Spring整合mybatis配置JNDI数据源](https://blog.csdn.net/mwx523037520036/article/details/127700054)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值