mybatis-plus 多数据源配置详解 包含pom,yml,config等配置

需要引入的pom


  4.0.0
	
		org.springframework.boot
	    spring-boot-starter-parent
	  	2.1.4.RELEASE
	     
	
  com.cqyx
  others
  0.0.1-SNAPSHOT
  
  
   


   
      maven-ali
      http://maven.aliyun.com/nexus/content/groups/public//
      
         true
      
      
         true
         always
         fail
      
   



		
		
			org.springframework.boot
			spring-boot-configuration-processor
			true
		
		
			org.projectlombok
			lombok
			true
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		

		
			org.springframework.boot
			spring-boot-starter-jdbc
		
		
			org.springframework.boot
			spring-boot-starter-web
		
	
    
	    org.mybatis.spring.boot
	    mybatis-spring-boot-starter
	    1.1.1
	

	
            com.baomidou
            dynamic-datasource-spring-boot-starter
            2.5.4
        

	
	    com.baomidou
	    mybatis-plus
	    2.1.2
	
		
            mysql
            mysql-connector-java
            8.0.12
        
	
	
		org.mybatis.caches
		mybatis-ehcache
		1.0.3
	
	
	
	    org.apache.velocity
	    velocity-engine-core
	    2.0
	
 		
		
		
			org.springframework.boot
			spring-boot-devtools
			true
		

    

	
		
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
			
	            org.apache.maven.plugins
	            maven-compiler-plugin
	            
	           
	                1.8
	                1.8
	                UTF-8
				    true
	                  
                    true
              
	            

	        
		

	

1.yml

server:
  port: 8888
  max-http-header-size: 1024000
spring:
  servlet:
    multipart:
      max-file-size: 1000MB
      max-request-size: 1000MB
  application:
    name: cqyx
  mvc:
    favicon:
      enabled: false
  datasource:
    ds1:
      url: jdbc:mysql://xxxx:3306/cqyx?characterEncoding=utf8&allowPublicKeyRetrieval=true&allowMultiQueries=true&serverTimezone=UTC&useSSL=false
      username: cf
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
      type: com.zaxxer.hikari.HikariDataSource
      hikari:  
        minimum-idle: 5
        maximum-pool-size: 15
        auto-commit: true
        idle-timeout: 30000
        pool-name: DatebookHikariCP
        max-lifetime: 1800000
        connection-timeout: 30000
        connection-test-query: SELECT 1
    ds2:
      url: jdbc:mysql://xxxx:3306/cqyx?characterEncoding=utf8&allowPublicKeyRetrieval=true&allowMultiQueries=true&serverTimezone=UTC&useSSL=false
      username: cqyx
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
      type: com.zaxxer.hikari.HikariDataSource
      hikari:  
        minimum-idle: 5
        maximum-pool-size: 15
        auto-commit: true
        idle-timeout: 30000
        pool-name: DatebookHikariCP
        max-lifetime: 1800000
        connection-timeout: 30000
        connection-test-query: SELECT 1        

#mybatis配置
mybatis:
  mapper-locations: classpath*:mybatis/*Mapper.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.cqyx.**.entity
  global-config:
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    
    
cqyx:    
  #是否开启定时任务
  openTask: 1

2.dataresource配置文件



import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {
	 //主数据源配置 ds1数据源
    @Primary
    @Bean(name = "ds1DataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSourceProperties ds1DataSourceProperties() {
        return new DataSourceProperties();
    }

    //主数据源 ds1数据源
    @Primary
    @Bean(name = "ds1DataSource")
    public DataSource ds1DataSource(@Qualifier("ds1DataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    //第二个ds2数据源配置
    @Bean(name = "ds2DataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.ds2")
    public DataSourceProperties ds2DataSourceProperties() {
        return new DataSourceProperties();
    }

    //第二个ds2数据源
    @Bean("ds2DataSource")
    public DataSource ds2DataSource(@Qualifier("ds2DataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }
}

3.mybatis-plus配置文件



import javax.sql.DataSource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
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.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.mapper.AutoSqlInjector;
import com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;





@Configuration
@MapperScan(basePackages ="com.cqyx.**.mapper*", sqlSessionTemplateRef  = "ds1SqlSessionTemplate")
public class MybatisPlusConfig {
	@Autowired
	private DataSource dataSource;

	@Autowired
	private MybatisProperties properties;

	@Autowired
	private ResourceLoader resourceLoader = new DefaultResourceLoader();

	@Autowired(required = false)
	private Interceptor[] interceptors;

	@Autowired(required = false)
	private DatabaseIdProvider databaseIdProvider;
	
	
	/**
	 *	 mybatis-plus分页插件
	 */
	@Primary
	@Bean("ds1PaginationInterceptor")
	public PaginationInterceptor paginationInterceptor() {
		PaginationInterceptor page = new PaginationInterceptor();
		page.setDialectType("mysql");
		return page;
	}
	
	/**
	 *	 mybatis-plus乐观锁插件
	 */
	@Primary
	@Bean("ds1OptimisticLocker")
	public OptimisticLockerInterceptor optimisticLockerInterceptor() {
		OptimisticLockerInterceptor oLocker = new OptimisticLockerInterceptor();
		return oLocker;
	}
	/**
	 * 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定
	 * 配置文件和mybatis-boot的配置文件同步
	 * @return
	 */
	@Primary
	@Bean("ds1SqlSessionFactory")
	public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
		MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
		
		mybatisPlus.setDataSource(dataSource);
		mybatisPlus.setVfs(SpringBootVFS.class);
		if (StringUtils.hasText(this.properties.getConfigLocation())) {
			mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
		}
		mybatisPlus.setConfiguration(properties.getConfiguration());
		if (!ObjectUtils.isEmpty(this.interceptors)) {
			mybatisPlus.setPlugins(this.interceptors);
		}
		MybatisConfiguration mc = new MybatisConfiguration();
		mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
		mybatisPlus.setConfiguration(mc);
		if (this.databaseIdProvider != null) {
			mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
		}
		if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
			mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
		}
		if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
			mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
		}
		if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
			mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
		}
		//ID自增
		GlobalConfiguration global = new GlobalConfiguration(new AutoSqlInjector());
		global.setIdType(IdType.AUTO.getKey());
		global.setDbColumnUnderline(true);
		mybatisPlus.setGlobalConfig(global);
		return mybatisPlus;
	}
	 	@Primary
	    @Bean(name = "ds1TransactionManager")
	    public DataSourceTransactionManager ds1TransactionManager(@Qualifier("ds1DataSource") DataSource dataSource) {
	        return new DataSourceTransactionManager(dataSource);
	    }

	    @Primary
	    @Bean(name = "ds1SqlSessionTemplate")
	    public SqlSessionTemplate ds1SqlSessionTemplate(@Qualifier("ds1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
	        return new SqlSessionTemplate(sqlSessionFactory);
	    }
}

 

你可能感兴趣的:(springboot,java全栈)