Spring-boot整合Mybatis-plus多数据源

官方文档 http://baomidou.oschina.io/mybatis-plus-doc/#/quick-start

开源地址: Github | OSChina

pom.xml引入依赖

  
        
            com.baomidou
            mybatis-plus-boot-starter
            2.2.0
        

application-dev.properties基本配置

#---------Mybatis-plus配置----------------------------------------

# 如果是放在src/main/java目录下 classpath:/com/yourpackage/*/mapper/*Mapper.xml
# 如果是放在resource目录 classpath:/mapper/*Mapper.xml
#mybatis-plus-mapper-locations: classpath:com/zklt/bigdata/web/demo/dao/*.xml
#实体扫描,多个package用逗号或者分号分隔
mybatis-plus-typeAliasesPackage:com.zklt.bigdata.web.demo.bean
#主键类型  0:"数据库ID自增", 1:"用户输",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
mybatis-plus-global-config-id-type: 3
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
mybatis-plus-global-config-field-strategy: 2
#驼峰下划线转换
mybatis-plus-global-config-db-column-underline: true
#刷新mapper 调试神器
#refresh-mapper: true
#数据库大写下划线转换
#capital-mode: true
# Sequence序列接口实现类配置
mybatis-plus-global-config-key-generator: com.baomidou.mybatisplus.incrementer.OracleKeyGenerator
#逻辑删除配置(下面3个配置)
mybatis-plus-global-config-logic-delete-value: 1
mybatis-plus-global-config-logic-not-delete-value: 0
mybatis-plus-global-config-sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
#自定义填充策略接口实现
mybatis-plus-global-config-meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler
mybatis-plus-global-config-configuration:
#配置返回数据库(column下划线命名&&返回java实体是驼峰命名),自动匹配无需as(没开启这个,SQL需要写as: select user_id as userId)
mybatis-plus-global-config-map-underscore-to-camel-case: true
mybatis-plus-global-config-cache-enabled: false
#配置JdbcTypeForNull, oracle数据库必须配置
mybatis-plus-global-config-jdbc-type-for-null: 'null'

spring-boot配置类

package com.zklt.bigdata.config;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
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.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

//todo Mybatis-plus 对phoenix的sql语句拼接 支持度不高,暂时废弃
@Configuration
@MapperScan("com.zklt.bigdata.web.demo.dao")
public class MybatisPlus4MysqlConfig {

    @Primary
    @Bean("mysqlSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:com/zklt/bigdata/web/demo/dao/*.xml"));
        sqlSessionFactory.setPlugins(new Interceptor[]{
                new PaginationInterceptor(),
                new PerformanceInterceptor(),
                new OptimisticLockerInterceptor()
        });
        return sqlSessionFactory.getObject();
    }


}
package com.zklt.bigdata.config;

import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

//todo Mybatis-plus 对phoenix的sql语句拼接 支持度不高,暂时废弃
@Configuration
@MapperScan("com.zklt.bigdata.web.phoenix.dao")
public class MybatisPlus4PhoenixConfig {

    @Bean("phoenixSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("phoenixDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:com/zklt/bigdata/web/phoenix/dao/*.xml"));
        sqlSessionFactory.setPlugins(new Interceptor[]{
                new PaginationInterceptor(),
                new PerformanceInterceptor(),
                new OptimisticLockerInterceptor()
        });
        return sqlSessionFactory.getObject();
    }

}

核心就是配置SqlSessionFactory
mybatis是这样配置

//    @Primary
    @Bean(name = "mysqlSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:com/zklt/bigdata/web/*/dao/*.xml"));
        return sessionFactoryBean.getObject();
    }

然后改为mybatis-plus的

 @Bean("phoenixSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("phoenixDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
        configuration.setJdbcTypeForNull(JdbcType.NULL);
        sqlSessionFactory.setConfiguration(configuration);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:com/zklt/bigdata/web/phoenix/dao/*.xml"));
        sqlSessionFactory.setPlugins(new Interceptor[]{
                new PaginationInterceptor(),
                new PerformanceInterceptor(),
                new OptimisticLockerInterceptor()
        });
        return sqlSessionFactory.getObject();
    }

不同数据源配置不同dao接口主要是设置这个

 sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath*:com/zklt/bigdata/web/phoenix/dao/*.xml"));

对了,随便放个多数据源配,使用阿里巴巴的druid,一个mysql数据源,一个phoenix(hbase)数据源

package com.zklt.bigdata.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * @Description: 多数据源配置 //// druid配置
 * @Author: peng.liu
 * @CreateDate: 2018/5/3 10:23
 */
@Configuration
public class DruidConfig {

    @Autowired
    private Environment env;

    //-----------数据源配置--------------

    //mysql
    @Primary
    @Bean("mysqlDataSource")
    @Qualifier("mysqlDataSource")
    @ConfigurationProperties("spring.datasource.druid.mysql")
    public DataSource mysqlDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    //phoenix
    @Bean("phoenixDataSource")
    @Qualifier("phoenixDataSource")
//    @ConfigurationProperties("spring.datasource.druid.phoenix")
    public DataSource phoenixDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.druid.phoenix.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.druid.phoenix.url"));
        return dataSource;
    }

    //---------JdbcTemplate配置------------------

    //mysql
    @Bean(name = "mysqlJdbcTemplate")
    public JdbcTemplate mysqlJdbcTemplate(@Qualifier("mysqlDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    //phoenix
    @Bean(name = "phoenixJdbcTemplate")
    public JdbcTemplate phoenixJdbcTemplate(@Qualifier("phoenixDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

}

最后测试一下,junit

package com.zklt.bigdata.web.mybatisplus;

import com.zklt.bigdata.utils.JsonUtil;
import com.zklt.bigdata.web.demo.bean.TestBean;
import com.zklt.bigdata.web.demo.dao.TestBean4MybatisPlusDao;
import com.zklt.bigdata.web.phoenix.bean.Test1Bean;
import com.zklt.bigdata.web.phoenix.dao.Test1Bean4MybatisPlusDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @Description:
 * @Author: peng.liu
 * @CreateDate: 2018/5/4 11:01
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1Bean4MybatisPlusDaoTest {


    @Autowired
    private TestBean4MybatisPlusDao dao;

    @Autowired
    private Test1Bean4MybatisPlusDao dao1;


    @Test
    public void test() {
        TestBean testBean = dao.selectById(1);
        System.err.println(JsonUtil.toString(testBean));
    }


    @Test
    public void test1(){
        Test1Bean test1Bean = dao1.selectById(1001);
        System.err.println(JsonUtil.toString(test1Bean));
    }

}

你可能感兴趣的:(Spring-boot整合Mybatis-plus多数据源)