springbootstartermybatis

3.spring boot mybatis druid多数据源

2017-04-11  本文已影响1863人  会灰的大飞狼

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- ... -->
    <dependencies>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency> 
        <!-- oracle驱动 -->
        <dependency>
            <groupId>cn.easyproject</groupId>
            <artifactId>ojdbc7</artifactId>
            <version>12.1.0.2.0</version>
        </dependency>
        <!-- druid数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>
        <!-- ... -->
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <!-- 如果没有该项配置,肯呢个devtools不会起作用,即应用不会restart -->
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
        <!-- 扫描src/main/java下面的xml文件. -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

2.application.yml

同一个数据源如果想配置多环境就参考

2.spring boot yml 多环境

3.在java config的形式配置数据源和mybatis

config/ds下配置数据源

MasterDataSourceConfig:

package com.yunchuang.config.ds;
import com.yunchuang.config.properties.MasterDataSourceProperties;
import com.yunchuang.utils.MyUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
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.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
 * @author 尹冬飞
 * @create 2017-04-07 9:57
 */
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = {MasterDataSourceConfig.PACKAGE1, MasterDataSourceConfig.PACKAGE2}, sqlSessionFactoryRef = MasterDataSourceConfig.NAME + "SqlSessionFactory")
public class MasterDataSourceConfig {
    @Autowired
    private MasterDataSourceProperties masterDataSourceProperties;
    // 精确到 master 目录,以便跟其他数据源隔离
    //dao目录
    static final String PACKAGE1 = "com.yunchuang.dao.master";
    static final String PACKAGE2 = "com.yunchuang.dao.other";
    //xml目录
    private static final String mapperLocation1 = "classpath:com/yunchuang/dao/master/*.xml";
    private static final String mapperLocation2 = "classpath:com/yunchuang/dao/other/*.xml";
    private static final String[] mapperLocations = {mapperLocation1, mapperLocation2};
    //全局名字前缀
    static final String NAME = "master";
    //数据源
    @Bean(name = NAME + "DataSource")
    @Primary
    public DataSource dataSource() {
        String driverClassName = masterDataSourceProperties.getDriverClassName();
        String url = masterDataSourceProperties.getUrl();
        String username = masterDataSourceProperties.getUsername();
        String password = masterDataSourceProperties.getPassword();
        return MyUtils.getDruidDataSource(driverClassName, url, username, password);
    }
    //事务管理器
    @Bean(name = NAME + "TransactionManager")
    @Primary
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
    //工厂
    @Bean(name = NAME + "SqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier(NAME + "DataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(MyUtils.resolveMapperLocations(mapperLocations));
        return sessionFactory.getObject();
    }
}

ClusterDataSourceConfig

package com.yunchuang.config.ds;
import com.yunchuang.config.properties.ClusterDataSourceProperties;
import com.yunchuang.utils.MyUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
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.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
 * 数据源配置
 *
 * @author 尹冬飞
 * @create 2017-04-07 9:57
 */
@Configuration
@MapperScan(basePackages = {ClusterDataSourceConfig.PACKAGE1}, sqlSessionFactoryRef = ClusterDataSourceConfig.NAME + "SqlSessionFactory")
public class ClusterDataSourceConfig {
    @Autowired
    private ClusterDataSourceProperties clusterDataSourceProperties;
    static final String PACKAGE1 = "com.yunchuang.dao.cluster";
    //xml目录
    private static final String mapperLocation1 = "classpath:com/yunchuang/dao/cluster/*.xml";
    private static final String[] mapperLocations = {mapperLocation1};
    //全局名字前缀
    static final String NAME = "cluster";
    @Bean(name = NAME + "DataSource")
    public DataSource dataSource() {
        String driverClassName = clusterDataSourceProperties.getDriverClassName();
        String url = clusterDataSourceProperties.getUrl();
        String username = clusterDataSourceProperties.getUsername();
        String password = clusterDataSourceProperties.getPassword();
        return MyUtils.getDruidDataSource(driverClassName, url, username, password);
    }
    @Bean(name = NAME + "TransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
    @Bean(name = NAME + "SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier(NAME + "DataSource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(MyUtils.resolveMapperLocations(mapperLocations));
        return sessionFactory.getObject();
    }
}

utils:解决xml路径为数组的问题

package com.yunchuang.utils;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * 工具包
 *
 * @author 尹冬飞
 * @create 2017-04-07 16:59
 */
public class MyUtils {
    public static DruidDataSource getDruidDataSource(String driverClassName, String url, String username, String password) {
        DruidDataSource dataSource = new DruidDataSource();
        //这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName
        dataSource.setDriverClassName(driverClassName);
        //连接数据库的url
        dataSource.setUrl(url);
        //连接数据库的用户名
        dataSource.setUsername(username);
        //连接数据库的密码
        dataSource.setPassword(password);
        //初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
        dataSource.setInitialSize(1);
        //最小连接池数量
        dataSource.setMinIdle(1);
        //最大连接池数量
        dataSource.setMaxActive(20);
        //获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
        dataSource.setMaxWait(1000);
        return dataSource;
    }
    /**
     * org.mybatis.spring.boot.autoconfigure包下MybatisProperties里面的方法直接拿来用
     *
     * @param mapperLocations xml路径数组
     * @return 资源数组
     */
    public static Resource[] resolveMapperLocations(String[] mapperLocations) {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<Resource> resources = new ArrayList();
        if (mapperLocations != null) {
            String[] var3 = mapperLocations;
            int var4 = var3.length;
            for (int var5 = 0; var5 < var4; ++var5) {
                String mapperLocation = var3[var5];
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                } catch (IOException var8) {
                    ;
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }
}

MasterDataSourceProperties和ClusterDataSourceProperties(同下)

package com.yunchuang.config.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * 数据源属性文件
 *
 * @author 尹冬飞
 * @create 2017-04-07 10:57
 */
@Component
@ConfigurationProperties(prefix = "spring.datasource.master")
public class MasterDataSourceProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    public String getDriverClassName() {
        return driverClassName;
    }
    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

dao接口:

package com.yunchuang.dao.master;
import com.yunchuang.domain.Person;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
/**
 * dao接口
 *
 * @author 尹冬飞
 * @create 2017-04-07 9:38
 */
@Mapper
//@Component不加也好使,加了是为了idea能认出来
@Component
public interface IPersonDao {
    Person loadById(Integer id);
}

这样service里就能调用了dao了.xml和dao接口放在一个包下就行.

上一篇下一篇

猜你喜欢

热点阅读