SpringBoot:多数据源配置

排除自动配置

springboot会自动读取配置文件,由于我们需要配置多数据源,所以要排除自动配置,在启动入口添加如下注解

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

配置数据源

在application.yml中配置两个数据源

spring:
  datasource:
    first:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/XXX?useUnicode=true&characterEncoding=UTF-8&useSSL=false
      username: XXX
      password: XXX
      type: com.alibaba.druid.pool.DruidDataSource
      initial-size: 1
      minIdle: 3
      maxActive: 20
      maxWait: 60000
      filters: stat,wall,slf4j
    second:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/XXX?useUnicode=true&characterEncoding=UTF-8&useSSL=false
      username: XXX
      password: XXX
      type: com.alibaba.druid.pool.DruidDataSource

创建配置文件封装类

@ConfigurationProperties注解指定数据来源 1.FirstDataProperties类

package com.ad.core.hope.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-08-31 13:46
 **/
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.first")
public class FirstDataProperties {
    String driverClassName;
    String url;
    String username;
    String password;
}

2.SecondDataProperties类

package com.ad.core.hope.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-08-31 13:47
 **/
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.second")
public class SecondDataProperties {
    String driverClassName;
    String url;
    String username;
    String password;
}

数据源配置

这里面的代码才是最重要的 注:@Primary必须使用该注解指定主数据源 @MapperScan指定路径下的mapper使用该数据源 1.FirstDataSourceConfig配置

package com.ad.core.hope.config;

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.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;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-08-02 20:16
 **/

@Configuration
@MapperScan(basePackages = "com.ad.core.hope.mapper.first",sqlSessionTemplateRef = "firstSqlSessionTemplate")
public class FirstDataSourceConfig {

    @Autowired
    private FirstDataProperties firstprop;

    //创建数据源
    @Bean(name="firstDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.first")

    public DataSource getFirstDataSource(){
        DataSource build = DataSourceBuilder.create()
                .driverClassName(firstprop.driverClassName)
                .url(firstprop.url)
                .username(firstprop.username)
                .password(firstprop.password).build();
     return build;
    }

    //创建SqlSessionFactory
    @Bean(name = "firstSqlSessionFactory")

    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception{
     SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
     bean.setDataSource(dataSource);
     return bean.getObject();
    }

    //创建事务管理器
    @Bean(name = "firstTransactionManager")

    public DataSourceTransactionManager firstTransactionManager(@Qualifier("firstDataSource") DataSource dataSource){
     return new DataSourceTransactionManager(dataSource);
    }

    //创建SqlSessionTemplate
    @Bean(name = "firstSqlSessionTemplate")

    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws  Exception{
     return new SqlSessionTemplate(sqlSessionFactory);
    }

    private Class getType(String type){
        try {
            return Class.forName(type);
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        return null;
    }
}

2.SecondDataSourceConfig配置

package com.ad.core.hope.config;

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.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;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-08-02 20:16
 **/

@Configuration
@MapperScan(basePackages = "com.ad.core.hope.mapper.second",sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class SecondDataSourceConfig {

    @Autowired
    private SecondDataProperties secondprop;

    //创建数据源
    @Bean(name="secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    @Primary
    public DataSource getSecondDataSource(){
        DataSource build = DataSourceBuilder.create()
                .driverClassName(secondprop.driverClassName)
                .url(secondprop.url)
                .username(secondprop.username)
                .password(secondprop.password).build();
        return build;
    }

    //创建SqlSessionFactory
    @Bean(name = "secondSqlSessionFactory")
    @Primary
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    //创建事务管理器
    @Bean(name = "secondTransactionManager")
    @Primary
    public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    //创建SqlSessionTemplate
    @Bean(name = "secondSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws  Exception{
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    private Class getType(String type){
        try {
            return Class.forName(type);
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        return null;
    }
}

实现Mapper

注:该mapper的路径必须和@MapperScan注解的指定路径一样 1.first路径下的mapepr

package com.ad.core.hope.mapper.first;

import com.ad.core.hope.enums.TestUserEnum;
import com.ad.core.hope.vo.base.TestVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface TestInterface {

    @Select("SELECT * FROM user")
    @Results({
            @Result(property = "sex", column = "sex", javaType = TestUserEnum.class),
            @Result(property = "name", column = "username")
    })
    List<TestVo> getAll();
}

2.second路径下的mapper

package com.ad.core.hope.mapper.second;

import com.ad.core.hope.model.admin.SysUser;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;

/**
 * @program:hope
 * @author:aodeng
 * @create:2018-09-02 17:25
 **/
@org.apache.ibatis.annotations.Mapper
public interface TestMapper{
    @Select("SELECT * FROM sys_user")
    @Results({
            @Result(property = "userid", column = "userId"),
            @Result(property = "username", column = "username")
    })
    List<SysUser> getAll();
}

Controller使用

使用@Autowired注解装配mapper使用

@Controller
public class TeseController {

    @Autowired
    private TestInterface testInterface;

    @Autowired
    private TestMapper testMapper;

    @RequestMapping("/login")
    public String login(Model model){
        //数据源first测试
        List<TestVo> list=testInterface.getAll();
        for(int i=0;i<list.size();i++){
            System.out.println("测试fisrt数据源"+list.get(i).getName());
        }
        //数据源second测试
        List<SysUser> user=testMapper.getAll();
        for(int i=0;i<user.size();i++){
            System.out.println("测试second数据源"+user.get(i).getUsername());
        }
        return "admin/system_login";
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yzgu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值