使用SpringBoot 配置Oracle和H2双数据源及问题

 更新时间:2021年11月18日 09:32:29   作者:TheBiiigBlue  
这篇文章主要介绍了使用SpringBoot 配置Oracle和H2双数据源及问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

在上节使用了H2之后感觉很爽,很轻便,正好有个项目要求简单,最好不适用外部数据库,于是就想着把H2数据库集成进来,这个系统已经存在了一个Oracle,正好练习下配置多数据源,而在配置多数据源时,H2的schema配置不生效真是花了我好长时间才解决。。。所以也记录一下

配置POM

<!-- oracle -->
 <dependency>
     <groupId>com.github.noraui</groupId>
     <artifactId>noraui</artifactId>
     <version>2.4.0</version>
 </dependency>
<!-- h2-->
 <dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <version>1.4.197</version>
 </dependency>
 <!-- mybatisplus -->
 <dependency>
 	  <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus-boot-starter</artifactId>
      <version>3.1.1</version>
 </dependency>

配置yml

spring:
  http:
    encoding:
      charset: UTF-8
      enabled: true
      force: true
  datasource:
    driver-class-name: org.h2.Driver
    schema: classpath:h2/schema-h2.sql
    data: classpath:h2/data-h2.sql
    jdbc-url: jdbc:h2:file:D:/Cache/IdeaWorkSpace/BigData/CustomerModel/src/main/resources/h2/data/h2_data
    username: root
    password: a123456
    initialization-mode: always
    oracle:
     driver-class-name: oracle.jdbc.driver.OracleDriver
     jdbc-url: jdbc:oracle:thin:@xxx:1521:cmis
     username: xxx
     password: xxx
  h2:
    console:
      enabled: true
      path: /h2-console

可以看到配置中配置了两个数据源,主数据源是H2,第二个数据源是Oracle,接下来是通过配置类来注入数据源

配置注入

配置H2主数据源

package com.caxs.warn.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
 * @Author: TheBigBlue
 * @Description:
 * @Date: 2019/9/18
 */
@Configuration
@MapperScan(basePackages = "com.caxs.warn.mapper.h2", sqlSessionFactoryRef = "h2SqlSessionFactory")
public class H2DSConfig {
    @Bean(name = "h2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "h2TransactionManager")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(this.dataSource());
    }
    @Bean(name = "h2SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("h2DataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sessionFactory.getObject();
    }
    @Bean(name = "h2Template")
    public JdbcTemplate h2Template(@Qualifier("h2DataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

配置oracle从数据源

package com.caxs.warn.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
/**
 * @Author: TheBigBlue
 * @Description:
 * @Date: 2019/9/18
 */
@Configuration
@MapperScan(basePackages = "com.caxs.warn.mapper.oracle",sqlSessionFactoryRef = "oracleSqlSessionFactory")
public class OracleDSConfig {
    @Bean(name = "oracleDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.oracle")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "oracleTransactionManager")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(this.dataSource());
    }
    @Bean(name = "oracleSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("oracleDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return sessionFactory.getObject();
    }
    @Bean(name = "oracleTemplate")
    public JdbcTemplate oracleTemplate(@Qualifier("oracleDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

问题

Schema “classpath:h2/schema-h2.sql” not found

  

经过上面的配置就可以使用双数据源了,但是当我们测试时会发现报如下错误:Schema “classpath:h2/schema-h2.sql” not found,这个问题我也是找了好久,因为在配置但数据源的时候没有这个问题的,在配置多数据源才有了这个问题。

在这里插入图片描述   

单数据源时,是直接SpringBoot自动配置DataSource的,这个时候是正常的,而当配置多数据源时,我们是通过@Configuration来配置数据源的,怀疑问题出在 DataSourceBuilder 创建数据源这个类上,而单数据源自动装载时不会出现这样的问题。然后百度搜了下这个DataSourceBuilder,看到文章中实例的配置中schema是这样写的:

package com.caxs.warn.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 * @Author: TheBigBlue
 * @Description: 服务启动后,初始化数据库
 * @Date: 2019/9/19
 */
@Component
public class ApplicationRunnerService implements ApplicationRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationRunnerService.class);
    @Autowired
    @Qualifier("h2Template")
    private JdbcTemplate h2Template;
    @Value("${invoke.schema.location}")
    private String schema;
    @Value("${invoke.data.location}")
    private String data;
    /**
     * @Author: TheBigBlue
     * @Description: 项目启动,执行sql文件初始化
     * @Date: 2019/9/19
     * @Param args:
     * @Return:
     **/
    @Override
    public void run(ApplicationArguments args) {
        String schemaContent = this.getFileContent(schema);
        String dataContent = this.getFileContent(data);
        h2Template.execute(schemaContent);
        h2Template.execute(dataContent);
    }
    /**
     * @Author: TheBigBlue
     * @Description: 获取classpath下sql文件内容
     * @Date: 2019/9/19
     * @Param filePath:
     * @Return:
     **/
    private String getFileContent(String filePath) {
        BufferedReader bufferedReader = null;
        String string;
        StringBuilder data = new StringBuilder();
        try {
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            bufferedReader = new BufferedReader(new InputStreamReader(classPathResource.getInputStream()));
            while ((string = bufferedReader.readLine()) != null) {
                data.append(string);
            }
        } catch (IOException e) {
            LOGGER.error("加载ClassPath资源失败", e);
        }finally {
            if(null != bufferedReader){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data.toString();
    }
}

在这里插入图片描述   

抱着尝试的态度改了下,发现果然没问题了!!原来是在SpringBoot2.0之后schema对应的DataSourceProperties类中schema属性是一个List,所以需要前面加 - (yml中加-映射集合),记录下防止后面再踩坑。

在这里插入图片描述

在这里插入图片描述

Table “USER” not found; SQL statement:

在这里插入图片描述   

这个问题也是在只有配置多数据源时才会碰到的问题,就是配置的spring.datasource.schema和spring.datasource.data无效。这个我看了下如果是配置单数据源,springboot自动加载Datasource,是没问题的,但是现在是我们自己维护的datasource: return DataSourceBuilder.create().build();所以感觉还是DataSourceBuilder在加载数据源的时候的问题,但是还是没有找到原因。有网友说必须加initialization-mode: ALWAYS这个配置,但是我配置后也是不能用的。

在这里插入图片描述   

最后没办法就配置了一个类,在springboot启动后,自己加载文件,读取其中的sql内容,然后用jdbcTemplate去执行了下,模拟了下初始化的操作。。。后面如果有时间再来解决这个问题。

package com.caxs.warn.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
 * @Author: TheBigBlue
 * @Description: 服务启动后,初始化数据库
 * @Date: 2019/9/19
 */
@Component
public class ApplicationRunnerService implements ApplicationRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationRunnerService.class);
    @Autowired
    @Qualifier("h2Template")
    private JdbcTemplate h2Template;
    @Value("${invoke.schema.location}")
    private String schema;
    @Value("${invoke.data.location}")
    private String data;
    /**
     * @Author: TheBigBlue
     * @Description: 项目启动,执行sql文件初始化
     * @Date: 2019/9/19
     * @Param args:
     * @Return:
     **/
    @Override
    public void run(ApplicationArguments args) {
        String schemaContent = this.getFileContent(schema);
        String dataContent = this.getFileContent(data);
        h2Template.execute(schemaContent);
        h2Template.execute(dataContent);
    }
    /**
     * @Author: TheBigBlue
     * @Description: 获取classpath下sql文件内容
     * @Date: 2019/9/19
     * @Param filePath:
     * @Return:
     **/
    private String getFileContent(String filePath) {
        BufferedReader bufferedReader = null;
        String string;
        StringBuilder data = new StringBuilder();
        try {
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            bufferedReader = new BufferedReader(new InputStreamReader(classPathResource.getInputStream()));
            while ((string = bufferedReader.readLine()) != null) {
                data.append(string);
            }
        } catch (IOException e) {
            LOGGER.error("加载ClassPath资源失败", e);
        }finally {
            if(null != bufferedReader){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data.toString();
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java去除字符串中空格的方法详解

    Java去除字符串中空格的方法详解

    这篇文章主要介绍了Java去除字符串中空格的方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • 一文教你搞定Java Optional类判空操作

    一文教你搞定Java Optional类判空操作

    有时项目组内做code review,会充斥着大量的、原始的、丑陋的判空语句。让整体的代码显得十分的臃肿庞大丑陋,那么怎么办呢?利用Optional这个jdk8中引入的类就可以优雅的处理,现在我们来详细讲解下这个类的使用和源码
    2022-10-10
  • springcloud检索中间件 ElasticSearch 分布式场景的使用

    springcloud检索中间件 ElasticSearch 分布式场景的使用

    单机的elasticsearch做数据存储,必然面临两个问题:海量数据存储问题、单点故障问题,本文重点给大家介绍springcloud检索中间件 ElasticSearch 分布式场景的运用,感兴趣的朋友跟随小编一起看看吧
    2023-10-10
  • Java中Servlet的生命周期

    Java中Servlet的生命周期

    这篇文章主要介绍了Java中Servlet的生命周期,Servlet 初始化后调用 init () 方法、Servlet 调用 service() 方法来处理客户端的请求、Servlet 销毁前调用 destroy() 方法,下面来看看具体的解析吧,需要的小伙伴可以参考一下
    2022-01-01
  • Spring-基于Spring使用自定义注解及Aspect实现数据库切换操作

    Spring-基于Spring使用自定义注解及Aspect实现数据库切换操作

    这篇文章主要介绍了Spring-基于Spring使用自定义注解及Aspect实现数据库切换操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • 一文搞懂Java顶层类之Object类的使用

    一文搞懂Java顶层类之Object类的使用

    java.lang.Object类是Java语言中的根类,即所有类的父类。它中描述的所有方法子类都可以使用。本文主要介绍了Object类中toString和equals方法的使用,感兴趣的小伙伴可以了解一下
    2022-11-11
  • 浅析Jmeter多用户token使用问题

    浅析Jmeter多用户token使用问题

    这篇文章主要介绍了Jmeter多用户token使用问题,通过具体的例子给大家介绍了Jmeter多用户token使用场景接口分析,需要的朋友可以参考下
    2021-10-10
  • java实现猜拳游戏试题

    java实现猜拳游戏试题

    这篇文章主要为大家详细介绍了java实现猜拳游戏试题,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-03-03
  • Java设计模式之观察者模式(Observer模式)

    Java设计模式之观察者模式(Observer模式)

    这篇文章主要介绍了Java设计模式之观察者模式(Observer模式),文中有非常详细的代码示例,对正在学习java的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-04-04
  • java  HashMap和HashTable的区别详解

    java HashMap和HashTable的区别详解

    这篇文章主要介绍了java HashMap和HashTable的区别详解的相关资料,需要的朋友可以参考下
    2016-12-12

最新评论