signed

QiShunwang

“诚信为本、客户至上”

spring-boot 2.3.3.RELEASE 整合oracle、mysql多数据源

2020/8/19 23:46:24   来源:

pom文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.diy.sigmund</groupId>
    <artifactId>spring-boot-multiple-data-sources</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>spring-boot-multiple-data-sources</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <!--    Connect to oracle    -->
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.4.0</version>
        </dependency>
        <!--    Connect to mysql    -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.yaml

spring:
  datasource:
    web:
      driver-class-name: oracle.jdbc.OracleDriver
      jdbc-url: jdbc:oracle:thin:@192.168.92.100:1521:orcl
      username: web
      password: 123456
    deploy:
      driver-class-name: oracle.jdbc.OracleDriver
      jdbc-url: jdbc:oracle:thin:@192.168.92.100:1521:orcl
      username: deploy
      password: 123456
    flower:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/flower?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password:
  mvc:
    view:
      prefix: classpath:/templates/
      suffix: .html
mybatis:
  config-location: classpath:config/mybatis/mybatis-config.xml
  mapper-locations: classpath:config/dao/*.xml

server:
  port: 8080
  servlet:
    context-path: /api/demo

主数据源配置


import javax.sql.DataSource;

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.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;

/**
 * basePackages:dao所在包
 * sqlSessionTemplateRef:表示dao使用的SqlSessionTemplate
 * 
 * @author yao liming
 * @since 2020/8/19 21:54
 */
@Configuration
@MapperScan(basePackages = "com.diy.sigmund.springbootmultipledatasources.dao.web",
    sqlSessionTemplateRef = "webSqlSessionTemplate")
public class DataSourceConfigWeb {

    @Bean(name = "webDataSource") // 定义bean名称
    @ConfigurationProperties(prefix = "spring.datasource.web") // 自定义数据源前缀
    @Primary // 自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者(主库),否则将抛出异常;从库不需要加该注解
    public DataSource DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "webSqlSessionFactory")
    @Primary
    public SqlSessionFactory SqlSessionFactory(@Qualifier("webDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(
            new PathMatchingResourcePatternResolver().getResources("classpath:/config/dao/web/*.xml"));
        return bean.getObject();
    }

    // 创建事务
    @Bean(name = "webTransactionManager")
    @Primary
    public DataSourceTransactionManager TransactionManager(@Qualifier("webDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    // 用于注入dao
    @Bean(name = "webSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate SqlSessionTemplate(@Qualifier("webSqlSessionFactory") SqlSessionFactory sqlSessionFactory)
        throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

从数据源配置

  • 在主数据源的基础上去掉@Primary,全局替换web即可

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <settings>
        <!-- 获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true"/>
        <!-- 使用列标签替换列别名 默认:true -->
        <setting name="useColumnLabel" value="true"/>
        <!-- 开启驼峰命名转换 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

单元测试

查询、更新都可满足


import com.diy.sigmund.springbootmultipledatasources.dao.deploy.TeacherMapper;
import com.diy.sigmund.springbootmultipledatasources.dao.web.StudentMapper;
import com.diy.sigmund.springbootmultipledatasources.entity.AdmireVO;
import com.diy.sigmund.springbootmultipledatasources.entity.Student;
import com.diy.sigmund.springbootmultipledatasources.entity.TeacherDO;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * @author yao liming
 * @since 2020/8/19 22:12
 */
@SpringBootTest
class AdmireVOMapperTest {
    @Autowired
    private AdmireVOMapper admireVOMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Test
    void select(){
        List<Student> all = studentMapper.getAll();
        Student student = all.stream().findFirst().get();
        student.setAge(18);
        int updateStudentByUserId = studentMapper.updateStudentByUserId(student);
        //1
        System.out.println(updateStudentByUserId);

        AdmireVO admireVO = admireVOMapper.selectByPrimaryKey(1);
        admireVO.setTel("13384759667");
        int updateByPrimaryKey = admireVOMapper.updateByPrimaryKey(admireVO);
        //1
        System.out.println(updateByPrimaryKey);

        List<TeacherDO> teachers = teacherMapper.getAll();
        System.out.println(teachers.stream().findAny().get().toString());
    }

}

关键文件路径

dao- com.diy.sigmund.springbootmultipledatasources.dao.web.StudentMapper
xml- classpath:/config/dao/web/StudentMapper.xml

ojdbc6jar获取

IDEA mysql&oracle mybatis-generator plugin插件 自动生成实体类和mapper.xml实战

console提示Cause: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.

  • spring.datasource.url 数据库的 JDBC URL。
  • 改为
  • spring.datasource.jdbc-url 用来重写自定义连接池
  • 参考jdbcUrl is required with driverClassName错误解决

console提示Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.

  • driver-class-name: com.mysql.jdbc.Driver
  • 改为
  • com.mysql.cj.jdbc.Driver

console提示Registered driver with driverClassName=oracle.jdbc.driver.OracleDriver was not found, trying direct instantiation.

  • driver-class-name: oracle.jdbc.driver.OracleDriver
  • 改为
  • oracle.jdbc.OracleDriver

资料参考

springboot整合mybatis(多数据源、mysql/Oracle数据库版)