欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot項(xiàng)目配置多數(shù)據(jù)庫(kù)連接的示例詳解

 更新時(shí)間:2023年12月27日 15:24:22   作者:相與還  
這篇文章主要介紹了springboot項(xiàng)目配置多數(shù)據(jù)庫(kù)連接的示例,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧

前言

之前編寫了一篇maven項(xiàng)目創(chuàng)建多數(shù)據(jù)庫(kù)的方法,現(xiàn)在對(duì)springboot更了解之后,將把springboot項(xiàng)目配置多數(shù)據(jù)庫(kù)的方法貼出來(lái)。
從項(xiàng)目開始創(chuàng)建到調(diào)用數(shù)據(jù)庫(kù)依次寫出來(lái)。

PS:本項(xiàng)目使用的是IDEA進(jìn)行創(chuàng)建

創(chuàng)建springboot項(xiàng)目

1.點(diǎn)擊創(chuàng)建新maven項(xiàng)目,然后下一步

2.輸入項(xiàng)目名稱,創(chuàng)建項(xiàng)目

3.創(chuàng)建完成之后,初始默認(rèn)結(jié)構(gòu)如下:

需要?jiǎng)?chuàng)建的文件夾結(jié)構(gòu)分類

以下截圖為進(jìn)行不同功能分類進(jìn)行創(chuàng)建的文件夾

文件說(shuō)明:

java文件都應(yīng)該在java文件夾下
資源文件都應(yīng)該放在resources下
bean: 存放實(shí)體對(duì)象
controller:存放控制層
service: 存放service層
db: 多數(shù)據(jù)庫(kù)配置
mapper:數(shù)據(jù)庫(kù)連接接口
tools:工具類
resources/mapper數(shù)據(jù)庫(kù)的增刪改查文件

以下為為配置多數(shù)據(jù)庫(kù)應(yīng)創(chuàng)建的文件,文件截圖和說(shuō)明如下:

java文件都應(yīng)該在java文件夾下
資源文件都應(yīng)該放在resources下
db: db文件夾下的文件為多數(shù)據(jù)庫(kù)配置代碼
mapper:com.mapper下的文件為編寫數(shù)據(jù)庫(kù)的增刪改查方法
MultipleDataApplication.java:?jiǎn)?dòng)類
resources/mapper下的文件數(shù)據(jù)庫(kù)的增刪改查`語(yǔ)句`文件
其中
resources/mapper下的MyDb1為對(duì)應(yīng)數(shù)據(jù)庫(kù)MyDb1的編寫數(shù)據(jù)庫(kù)語(yǔ)句文件
resources/mapper下的MyDb2為對(duì)應(yīng)數(shù)據(jù)庫(kù)MyDb2的編寫數(shù)據(jù)庫(kù)語(yǔ)句文件
applition.yml:springboot項(xiàng)目配置文件
pom.xml:依賴配置文件

導(dǎo)入pom依賴

初始pom.xml配置文件代碼為:

要完成多數(shù)據(jù)庫(kù)配置,需要至少導(dǎo)入以下依賴:

第一個(gè):springboot依賴
第二個(gè):mybatis
第三個(gè):數(shù)據(jù)庫(kù)驅(qū)動(dòng)依賴
第四個(gè): 阿里巴巴數(shù)據(jù)庫(kù)連接池

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>
    <groupId>org.example</groupId>
    <artifactId>multipleDataConnection</artifactId>
    <version>1.0-SNAPSHOT</version>
<!--    springboot管理配置-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/>
    </parent>
    <dependencies>
        <!-- springboot依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mybatis-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
        <!-- mysql數(shù)據(jù)庫(kù)驅(qū)動(dòng) -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 數(shù)據(jù)庫(kù)連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.9</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
</project>

編寫配置xml(yml)

在項(xiàng)目配置信息,需要編寫啟動(dòng)端口,數(shù)據(jù)庫(kù)連接以及連接池和mybatis的配置信息
具體配置信息如下:

以下為application.yml格式配置文件代碼

server:
  port: 9021
  servlet:
    context-path: /啟動(dòng)路徑
#    數(shù)據(jù)庫(kù)
spring:
  datasource:
    MyDb1:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://數(shù)據(jù)庫(kù)ip:3306/數(shù)據(jù)庫(kù)名
      username: 用戶名
      password: 密碼
    MyDb2:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://數(shù)據(jù)庫(kù)ip:3306/數(shù)據(jù)庫(kù)名
      username: 用戶名
      password: 密碼
    druid:
      #最大活躍數(shù)
      maxActive: 20
      #初始化數(shù)量
      initialSize: 1
      #最大連接等待超時(shí)時(shí)間
      maxWait: 60000
      #打開PSCache,并且指定每個(gè)連接PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      #通過(guò)connectionProperties屬性來(lái)打開mergeSql功能;慢SQL記錄
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      minIdle: 1
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 1 from dual
      validationQuery1: select 1
      # 注意 有的數(shù)據(jù)庫(kù)不支持select 1 from dual 在配置處需要修改為下方的select 1
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      #配置監(jiān)控統(tǒng)計(jì)攔截的filters,去掉后監(jiān)控界面sql將無(wú)法統(tǒng)計(jì),'wall'用于防火墻
      filters: stat, wall, log4j
      # 合并多個(gè)DruidDataSource的監(jiān)控?cái)?shù)據(jù)
      use-global-data-source-stat: true
mybatis:
  configuration:
    map-underscore-to-camel-case: true
    # 全局的sql執(zhí)行超時(shí)時(shí)間(單位s) 當(dāng)sql執(zhí)行時(shí)間超過(guò)1s,就會(huì)斷開操作了,起到保護(hù)數(shù)據(jù)庫(kù)服務(wù)的作用
    default-statement-timeout: 5
    # 流式
    default-fetch-size: 100
    # 配置查詢返回最大數(shù)量
  max_row: 10000

注意: spring下的datasource,為編寫多個(gè)數(shù)據(jù)庫(kù)的連接信息,ip賬號(hào)密碼等。
其中作為演示,我把兩個(gè)數(shù)據(jù)庫(kù)名稱分別標(biāo)注命名為MyDb1和MyDb2

validationQuery:為驗(yàn)證不同的數(shù)據(jù)庫(kù)連接的語(yǔ)句,不同數(shù)據(jù)庫(kù)的驗(yàn)證語(yǔ)句不同
不同數(shù)據(jù)庫(kù)驗(yàn)證語(yǔ)句如下:

數(shù)據(jù)庫(kù)validationQuery驗(yàn)證語(yǔ)句
hsqldbselect 1 from INFORMATION_SCHEMA.SYSTEM_USERS
Oracleselect 1 from dual
DB2select 1 from sysibm.sysdummy1
MySqlselect 1
Microsoft SqlServerselect 1
postgresqlselect version()
ingresselect 1
derbyselect 1
H2select 1

這個(gè)驗(yàn)證連接語(yǔ)句需要根據(jù)自己連的數(shù)據(jù)庫(kù)進(jìn)行更改配置語(yǔ)句

編寫resource的mapper查詢

在resource/mapper里,我創(chuàng)建了兩個(gè)文件MyDb1Mapper.xmlMyDb2Mapper.xml,用來(lái)標(biāo)識(shí)兩個(gè)不同數(shù)據(jù)庫(kù)的連接的文件.
其中MyDb1Mapper.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.mapper.MyDb1.MyDb1Mapper">
</mapper>

其中MyDb2Mapper.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.mapper.MyDb2.MyDb2Mapper">
</mapper>

注意:此處`namespace`路徑為數(shù)據(jù)庫(kù)接口文件路徑

編寫mapper接口

在com.demo.mapper下有兩個(gè)文件夾,分別標(biāo)識(shí)不同的數(shù)據(jù)庫(kù)接口文件,
其中mapper/MyDb1Mapper.java文件代碼如下(不包含功能):

package com.mapper.MyDb1;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MyDb1Mapper {
}

其中mapper/MyDb2Mapper.java文件代碼如下(不包含功能):

package com.mapper.MyDb2;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface MyDb2Mapper {
}

名稱隨便命名,自己容易區(qū)別就行

編寫多數(shù)據(jù)庫(kù)配置

如你所見,在上方截圖中我編寫了四個(gè)文件作為數(shù)據(jù)庫(kù)配置,如你需要根據(jù)它去刪除或添加多個(gè)數(shù)據(jù)庫(kù),把里面的DbMyDb1ConfigDbMyDb2Config換成你自己的數(shù)據(jù)庫(kù)配置即可(根據(jù)yml里,你數(shù)據(jù)庫(kù)的配置修改)
同時(shí),在DataSourceConfig里增減需要的數(shù)據(jù)庫(kù)配置代碼,復(fù)制修改名稱即可
MybatisInterceptor不需要修改。

如果有更多的數(shù)據(jù)庫(kù)需要連接進(jìn)來(lái),只需要在`DataSourceConfig`里添加新數(shù)據(jù)庫(kù)的配置代碼,復(fù)制
`DbMyDb1Config`和`DbMyDb2Config`其中一個(gè)文件進(jìn)行修改DataSourceConfig對(duì)應(yīng)名稱配置即可

其中,DataSourceConfig代碼如下:

package com.db;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
public class DataSourceConfig {
    @Value("${spring.datasource.MyDb1.driver-class-name}")
    private String MyDb1Driver;
    @Value("${spring.datasource.MyDb1.url}")
    private String MyDb1Url;
    @Value("${spring.datasource.MyDb1.username}")
    private String MyDb1Username;
    @Value("${spring.datasource.MyDb1.password}")
    private String MyDb1Password;
    @Value("${spring.datasource.MyDb2.driver-class-name}")
    private String MyDb2Driver;
    @Value("${spring.datasource.MyDb2.url}")
    private String MyDb2Url;
    @Value("${spring.datasource.MyDb2.username}")
    private String MyDb2Username;
    @Value("${spring.datasource.MyDb2.password}")
    private String MyDb2Password;
    @Value("${spring.datasource.druid.maxActive}")
    private Integer maxActive;
    @Value("${spring.datasource.druid.initialSize}")
    private Integer initialSize;
    @Value("${spring.datasource.druid.maxWait}")
    private Integer maxWait;
    @Value("${spring.datasource.druid.poolPreparedStatements}")
    private boolean poolPreparedStatements;
    @Value("${spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize}")
    private Integer maxPoolPreparedStatementPerConnectionSize;
    @Value("${spring.datasource.druid.minIdle}")
    private Integer minIdle;
    @Value("${spring.datasource.druid.connectionProperties}")
    private String connectionProperties;
    @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
    private Integer timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
    private Integer minEvictableIdleTimeMillis;
    @Value("${spring.datasource.druid.validationQuery}")
    private String validationQuery;
    @Value("${spring.datasource.druid.validationQuery1}")
    private String validationQuery1;
    @Value("${spring.datasource.druid.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${spring.datasource.druid.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${spring.datasource.druid.testOnReturn}")
    private boolean testOnReturn;
    @Value("${spring.datasource.druid.filters}")
    private String filters;
    @Value("${spring.datasource.druid.use-global-data-source-stat}")
    private boolean useGlobalDataSourceStat;
    @Bean(name = "dsMyDb1")
    @Qualifier("dsMyDb1")
    public DataSource dataSourceMyDb1() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(MyDb1Url);
        datasource.setUsername(MyDb1Username);
        datasource.setPassword(MyDb1Password);
        datasource.setDriverClassName(MyDb1Driver);
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
//        try {
//            datasource.setFilters(filters);
//        } catch (SQLException e) {
//            System.err.println("druid configuration initialization filter: " + e);
//        }
        datasource.setConnectionProperties(connectionProperties);
        datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
        return datasource;
    }
    @Bean(name = "dsMyDb2")
    @Qualifier("dsMyDb2")
    public DataSource dataSourceMyDb2() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(MyDb2Url);
        datasource.setUsername(MyDb2Username);
        datasource.setPassword(MyDb2Password);
        datasource.setDriverClassName(MyDb2Driver);
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
//        try {
//            datasource.setFilters(filters);
//        } catch (SQLException e) {
//            System.err.println("druid configuration initialization filter: " + e);
//        }
        datasource.setConnectionProperties(connectionProperties);
        datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
        return datasource;
    }
}

其中MybatisInterceptor代碼如下:

package com.db;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Properties;
@Component
@Intercepts({@Signature(type = Executor.class, method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class MybatisInterceptor implements Interceptor {
    @Value("${mybatis.max_row}")
    private Integer max_row;
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        invocation.getArgs()[2] = new RowBounds(0, (null == max_row || 0 == max_row) ? 10000 : max_row);
        return invocation.proceed();
    }
    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }
    @Override
    public void setProperties(Properties properties) {
    }
}

其中DbMyDb1Config 代碼如下:

package com.db;
import org.apache.ibatis.plugin.Interceptor;
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.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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.annotation.Resource;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.mapper.MyDb1"}, sqlSessionFactoryRef = "SqlSessionFactoryMyDb1")
public class DbMyDb1Config {
    @Autowired
    private MybatisInterceptor mybatisInterceptor;
    @Resource
    @Qualifier("dsMyDb1")
    private DataSource dsMyDb1;
    /**
     * 創(chuàng)建sqlsessionfactory
     */
    @Bean(name = {"SqlSessionFactoryMyDb1"})
    @Primary
    public SqlSessionFactory sqlSessionFactoryMyDb1() throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dsMyDb1);
        org.springframework.core.io.Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/MyDb1/*.xml");
        sessionFactoryBean.setMapperLocations(resources);
        sessionFactoryBean.setPlugins(new Interceptor[]{mybatisInterceptor});
        return sessionFactoryBean.getObject();
    }
    @Bean(name = {"dbMyDb1TransactionManager"})
    @Primary
    public DataSourceTransactionManager dbMyDb1TransactionManager(@Qualifier("dsMyDb1") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Bean
    @Primary
    public SqlSessionTemplate dbMyDb1SqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryMyDb1());
    }
}

其中DbMyDb2Config代碼如下

package com.db;
import org.apache.ibatis.plugin.Interceptor;
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.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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.annotation.Resource;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.Invoice.mapper.MyDb2"}, sqlSessionFactoryRef = "SqlSessionFactoryMyDb2")
public class DbMyDb2Config {
    @Autowired
    private MybatisInterceptor mybatisInterceptor;
    @Resource
    @Qualifier("dsMyDb2")
    private DataSource dsMyDb2;
    /**
     * 創(chuàng)建sqlsessionfactory
     */
    @Bean(name = {"SqlSessionFactoryMyDb2"})
    public SqlSessionFactory sqlSessionFactoryMyDb2() throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dsMyDb2);
        org.springframework.core.io.Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/MyDb2/*.xml");
        sessionFactoryBean.setMapperLocations(resources);
        sessionFactoryBean.setPlugins(new Interceptor[]{mybatisInterceptor});
        return sessionFactoryBean.getObject();
    }
    @Bean(name = {"dbMyDb2TransactionManager"})
    public DataSourceTransactionManager dbMyDb2TransactionManager(@Qualifier("dsMyDb2") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    @Bean
    public SqlSessionTemplate dbMyDb2SqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryMyDb2());
    }
}

注意:

MyDb1Config和MyDb2Config的代碼有一個(gè)很重要的區(qū)別,必須有且只有一個(gè)數(shù)據(jù)庫(kù)作為主數(shù)據(jù)庫(kù)。
用注解@primary標(biāo)注
可以仔細(xì)看MyDb1Config和MyDb2Config的這個(gè)區(qū)別,他們的區(qū)別就在于@primary

啟動(dòng)類

Application.java啟動(dòng)類代碼如下:

package com;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * description: 啟動(dòng)類
 * */
@SpringBootApplication
@MapperScan("com.mapper")
public class MultipleDataApplication {
    public static void main(String[] args) {
        SpringApplication.run(MultipleDataApplication.class,args);
    }
}

運(yùn)行成功截圖

在這里插入圖片描述

在這里插入圖片描述

異常處理

在連接某些數(shù)據(jù)庫(kù),可能會(huì)出現(xiàn)一些異常,如寫了接口方法找不到、但確實(shí)有寫;如hana的時(shí)候遇到一個(gè)找不到對(duì)應(yīng)的表,但是確實(shí)是有這個(gè)表在數(shù)據(jù)庫(kù),可以嘗試簡(jiǎn)化DataSourceConfig的各個(gè)數(shù)據(jù)庫(kù)配置

以下代碼為最原始簡(jiǎn)單的連接數(shù)據(jù)庫(kù)的配置,加上阿里巴巴連接池的目的是為了優(yōu)化數(shù)據(jù)庫(kù)連接
所有的數(shù)據(jù)庫(kù)連接配置都可以用以下的代碼配置

    @Bean(name = "dsDemo")
    @Qualifier("dsDemo")
    public DataSource dataSourceErp() {
        return DataSourceBuilder.create()
                .type(DruidDataSource.class)
                .driverClassName(DemoDriver)
                .url(DemopUrl)
                .username(DemoUsername)
                .password(DemoPassword)
                .build();
    }

結(jié)語(yǔ)

以上基于springboot多數(shù)據(jù)庫(kù)連接的項(xiàng)目我是重新新建項(xiàng)目后一步步驗(yàn)證后發(fā)出來(lái)的。測(cè)試有效。
如果后續(xù)有更完善的內(nèi)容,將會(huì)在這邊進(jìn)行更新出來(lái)。
希望能幫助到大家。

到此這篇關(guān)于springboot項(xiàng)目配置多數(shù)據(jù)庫(kù)連接的文章就介紹到這了,更多相關(guān)springboot配置多數(shù)據(jù)庫(kù)連接內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論