SpringBoot添加多个数据源

SpringBoot添加多个数据源

  • 1.启动类
  • 2.application.properties
  • 3.配置类
  • 4.新建服务类
  • 5.Mapper
  • 6.注意

1.启动类

package com.jack.hhitseat;

import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling//启动定时任务
//@MapperScan("com.jack.hhitseat.mapper.*")
//EnableAutoConfiguration注解,关闭springBoot关于mybatis的一些自动注入
@EnableAutoConfiguration(exclude = {
     DataSourceAutoConfiguration.class,DataSourceTransactionManagerAutoConfiguration.class, MybatisAutoConfiguration.class})
public class HhitseatApplication{
     

	public static void main(String[] args) {
     
		SpringApplication.run(HhitseatApplication.class, args);
	}
}

2.application.properties

server.port=8085
debug=true 
##打开sql执行语句打印日志

###############################MySQL数据库配置###############################
# 数据库1
spring.datasource.jdbc-url=jdbc:mysql://127.0.0.1:3306/hhitseat?characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=false
spring.datasource.username=root
spring.datasource.password=Jack..
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 数据库2
spring.datasource.ginfo.jdbc-url=jdbc:mysql://139.999.666.888:3306/hhitseat?characterEncoding=UTF-8&serverTimezone=GMT%2b8&useSSL=false
spring.datasource.ginfo.username=root
spring.datasource.ginfo.password=JackWei..
spring.datasource.ginfo.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.ginfo.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.druid.initial-size=5  
spring.datasource.druid.min-idle=5  
spring.datasource.druid.max-active=20  
spring.datasource.druid.max-wait=60000  
spring.datasource.druid.time-between-eviction-runs-millis=60000  
spring.datasource.druid.min-evictable-idle-time-millis=300000  
spring.datasource.druid.validation-query=SELECT 1 FROM DUAL  
spring.datasource.druid.test-while-idle=true  
spring.datasource.druid.test-on-borrow=false  
spring.datasource.druid.test-on-return=false  
spring.datasource.druid.pool-prepared-statements=true  
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20  
spring.datasource.druid.filters=stat,wall,log4j  
logging.level.org.springframework.boot.autoconfigure=ERROR 

# Freemarker 模板配置
#表示所有的访问都经过静态资源路径;
spring.mvc.static-path-pattern=/**
#在这里表示配置静态资源根路径
spring.resources.static-locations=classpath:/static/
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/html/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html

#config page 配置分页插件
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params = count=countSql
pagehelper.pageSize=5

3.配置类

package com.jack.hhitseat.config;

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.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;

@Configuration
@MapperScan(basePackages = "com.jack.hhitseat.mapper.ginfo",sqlSessionFactoryRef = "ginfoSqlSessionFactory")
public class GinfoDataSourceConfig {
     
	@Primary
    @Bean(name = "ginfoDataSource")
    @ConfigurationProperties("spring.datasource.ginfo")
    public DataSource masterDataSource(){
     
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "ginfoSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("ginfoDataSource") DataSource dataSource) throws Exception {
     
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:com/jack/hhitseat/mapper/ginfo/*.xml"));
        return sessionFactoryBean.getObject();
    }
}

package com.jack.hhitseat.config;

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.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;

@Configuration
@MapperScan(basePackages = "com.jack.hhitseat.mapper.main",sqlSessionFactoryRef = "mainSqlSessionFactory")
public class MainDataSourceConfig {
     
	@Primary
    @Bean(name = "mainDataSource")
    @ConfigurationProperties("spring.datasource")
    public DataSource masterDataSource(){
     
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "mainSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mainDataSource") DataSource dataSource) throws Exception {
     
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:com/jack/hhitseat/mapper/main/*.xml"));
        return sessionFactoryBean.getObject();
    }
}

4.新建服务类

package com.jack.hhitseat.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jack.hhitseat.bean.Log;
import com.jack.hhitseat.bean.LogExample;
import com.jack.hhitseat.mapper.ginfo.GLogMapper;

@Service("ginfoLogService")
public class GinfoLogService {
     
	@Autowired
	private GLogMapper gLogMapper;
	
	public List<Log> listLogByDate(String date){
     
		LogExample example = new LogExample();
		example.createCriteria().andCreateTimeGreaterThan(date);
		return gLogMapper.selectByExample(example);
	}
}

5.Mapper

package com.jack.hhitseat.mapper.ginfo;

import com.jack.hhitseat.bean.Log;
import com.jack.hhitseat.bean.LogExample;
import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

public interface GLogMapper {
     

    List<Log> selectByExample(LogExample example);
}


<mapper namespace="com.jack.hhitseat.mapper.ginfo.GLogMapper">
  <resultMap id="BaseResultMap" type="com.jack.hhitseat.bean.Log">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="user_id" jdbcType="INTEGER" property="userId" />
    <result column="status" jdbcType="INTEGER" property="status" />
    <result column="count" jdbcType="INTEGER" property="count" />
    <result column="create_time" jdbcType="VARCHAR" property="createTime" />
  resultMap>
mapper>

6.注意

  1. 启动类要关闭自动注解
  2. application.properties配置要正确
  3. 配置类对应好包和对应的名称
  4. Mapper的xml文件注意不要重复,对应好文件
    SpringBoot添加多个数据源_第1张图片
    参考博客:https://blog.csdn.net/zifengye520/article/details/81947392

你可能感兴趣的:(技术分享,浩哥的JAVA之路,访问多个数据库,SpringBoot,Spring访问多个数据库)