SpringBoot集成Mybatis多数据源(学习笔记)

断了今生、忘了曾经 提交于 2019-12-18 16:37:20

SpringBoot集成Mybatis 多数据源

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>

    <artifactId>spring-boot-demo-orm-mybatis</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-demo-orm-mybatis</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>com.zhihao</groupId>
        <artifactId>spring-boot-demo</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <mybatis.version>1.3.2</mybatis.version>
    </properties>

    <dependencies>
      <!--mybatis依赖  注意demo没有web依赖 无法启动启动类-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>

      <!--使用阿里巴巴的德鲁伊作为数据源-->
      <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
      </dependency>
        
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>spring-boot-demo-orm-mybatis</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.yml:

server:
  port: 19999
spring:
  datasource:
    zhuyao:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/demo?serverTimezone=UTC
      username: root
      password: root
      type: com.alibaba.druid.pool.DruidDataSource
      druid:
        initial-size: 5
        min-idle: 5
        max-active: 20
        max-wait: 60000
        time-between-eviction-runs-millis: 60000
        min-evictable-idle-time-millis: 300000
    ciyao:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/spring_boot?serverTimezone=UTC
      username: root
      password: root
      type: com.alibaba.druid.pool.DruidDataSource
      druid:
        initial-size: 5
        min-idle: 5
        max-active: 20
        max-wait: 60000
        time-between-eviction-runs-millis: 60000
        min-evictable-idle-time-millis: 300000
#下划线_驼峰配置
mybatis:
  configuration:
    map-underscore-to-camel-case: true

PrimaryDataSourceConfig.java:

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

import javax.sql.DataSource;

/**
 * <p>
 * mybatis多数据源配置 - 主数据源
 * </p>
 */
@Configuration
//主包扫描  和提供mapper接口的指定主数据源的sql会话模板
@MapperScan(basePackages = "com.zhihao.orm.mybatis.mapper", sqlSessionTemplateRef = "PrimarySqlSessionTemplate")
public class PrimaryDataSourceConfig {


    /**
     * 扫描spring.datasource.zhuyao开头的配置信息
     *
     * @return 数据源配置信息
     */
    @Primary
    @Bean(name = "PrimaryDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.zhuyao")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 获取主库数据源对象
     *
     * @param dataSourceProperties 注入名为primaryDataSourceProperties的bean
     * @return 数据源对象
     */
    @Primary
    @Bean(name = "PrimaryDataSource")
    public DataSource dataSource(@Qualifier("PrimaryDataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }


    /**
     * 创建 SqlSessionFactory
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "PrimarySqlSessionFactory")
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("PrimaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/*.xml"));
        return bean.getObject();
    }


    /**
     * 配置事务管理
     * @param dataSource
     * @return
     */
    @Bean(name = "PrimaryTransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("PrimaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 配置SqlSessionTemplate 模板
     * @param sqlSessionFactory
     * @return
     */
    @Bean(name = "PrimarySqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("PrimarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

CiyaoDataSourceConfig.java:

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.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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;

/**
 * <p>
 * mybatis多数据源配置 - 次数据源
 * </p>
 *
 */
@Configuration
//次包扫描  和提供mapper接口的指定次数据源的sql会话模板
@MapperScan(basePackages = "com.zhihao.orm.mybatis.mapper2", sqlSessionTemplateRef = "ciyaoSqlSessionTemplate")
public class CiyaoDataSourceConfig {

    /**
     * 扫描spring.datasource.ciyao开头的配置信息
     *
     * @return 次数据源配置信息
     */
    @Bean(name = "ciyaoDataSourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.ciyao")
    public DataSourceProperties dataSourceProperties() {
        return new DataSourceProperties();
    }

    /**
     * 获取次主库数据源对象
     *
     * @param dataSourceProperties 注入名为ciyaoDataSourceProperties的bean
     * @return 数据源对象
     */
    @Bean(name = "ciyaoDataSource")
    public DataSource dataSource(@Qualifier("ciyaoDataSourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }


    /**
     * 创建 SqlSessionFactory
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "ciyaoSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("ciyaoDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers2/*.xml"));
        return bean.getObject();
    }


    /**
     * 配置事务管理
     * @param dataSource
     * @return
     */
    @Bean(name = "ciyaoTransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("ciyaoDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 配置SqlSessionTemplate 模板
     * @param sqlSessionFactory
     * @return
     */
    @Bean(name = "ciyaoSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("ciyaoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

User.java

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * <p>
 * 用户实体类
 * </p>
 * @description: 用户实体类
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    private Long id;

    /**
     * 用户名
     */
    private String name;
		.........
}

mapper/PrimaryUserMapper.java:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.List;

/**
 * <p>
 * User Mapper
 * </p>
 */
@Mapper
@Qualifier("PrimarySqlSessionTemplate") //指定使用主数据源模板
public interface PrimaryUserMapper {

    /**
     * 查询所有用户
     *
     * @return 用户列表
     */
    @Select("SELECT * FROM user")
    List<User> selectAllUser();

    /**
     * 根据id查询用户
     *
     * @param id 主键id
     * @return 当前id的用户,不存在则是 {@code null}
     */
    @Select("SELECT * FROM orm_user WHERE id = #{id}")
    User selectUserById(@Param("id") Long id);

    /**
     * 保存用户
     *
     * @param user 用户
     * @return 成功 - {@code 1} 失败 - {@code 0}
     */
    int saveUser(@Param("user") User user);

}

mapper2/User2Mapper.java:

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.List;

/**
 * <p>
 * User Mapper
 * </p>
 *
 */
@Mapper
@Qualifier("ciyaoSqlSessionTemplate") //指定使用次数据源模板
public interface User2Mapper {

    /**
     * 查询所有用户
     *
     * @return 用户列表
     */
    @Select("SELECT * FROM user")
    List<User2> selectAllUser();

    /**
     * 根据id查询用户
     *
     * @param id 主键id
     * @return 当前id的用户,不存在则是 {@code null}
     */
    @Select("SELECT * FROM orm_user WHERE id = #{id}")
    User2 selectUserById(@Param("id") Long id);

    /**
     * 保存用户
     *
     * @param user 用户
     * @return 成功 - {@code 1} 失败 - {@code 0}
     */
    int saveUser(@Param("user") User2 user);

}

mappers/PrimaryUserMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhihao.orm.mybatis.mapper.PrimaryUserMapper">

    <insert id="saveUser">
        INSERT INTO `user` (`id`,
                                `name` )
        VALUES (#{user.id},
                #{user.name})
    </insert>

</mapper>

mappers2/UserMapper2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhihao.orm.mybatis.mapper.User2Mapper">

    <insert id="saveUser">
        INSERT INTO `user` (`id`,
                                `name` )
        VALUES (#{user.id},
                #{user.name})
    </insert>

</mapper>

测试:UserMapperTest.java

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * <p>
 * UserMapper 测试类
 * </p>
 *
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private User2Mapper user2Mapper;


    /**
     * 测试 主要数据源 查询
     */
    @Test
    public void selectAllUsers() {
        List<User> userList = userMapper.selectAllUser();
        System.out.println(userList);
    }

    /**
     * 测试 次要数据源 查询
     */
    @Test
    public void selectAllUserssss() {
        List<User> userList = user2Mapper.selectAllUser();
        System.out.println(userList);
    }

    /**
     * 测试 主要数据源 保存
     */
    @Test
    public void saveUser() {
        User user = new User(88L,"张韶涵");
        int i = userMapper.saveUser(user);
        System.out.println(i);
    }

    /**
     * 测试 次要数据源 保存
     */
    @Test
    public void saveUser2() {
        User user2 = new User(88L,"张韶涵");
        int i = user2Mapper.saveUser(user2);
        System.out.println(i);
    }

}

其他层 使用方式一样!

参考资料:

基于SpirngBoot2.0+ 的 SpringBoot+Mybatis 多数据源配置: https://juejin.im/post/5c07e59851882526a6440e53

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!