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

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

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

前言

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

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

創(chuàng)建springboot項目

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

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

3.創(chuàng)建完成之后,初始默認結構如下:

需要創(chuàng)建的文件夾結構分類

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

文件說明:

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

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

java文件都應該在java文件夾下
資源文件都應該放在resources下
db: db文件夾下的文件為多數(shù)據(jù)庫配置代碼
mapper:com.mapper下的文件為編寫數(shù)據(jù)庫的增刪改查方法
MultipleDataApplication.java:啟動類
resources/mapper下的文件數(shù)據(jù)庫的增刪改查`語句`文件
其中
resources/mapper下的MyDb1為對應數(shù)據(jù)庫MyDb1的編寫數(shù)據(jù)庫語句文件
resources/mapper下的MyDb2為對應數(shù)據(jù)庫MyDb2的編寫數(shù)據(jù)庫語句文件
applition.yml:springboot項目配置文件
pom.xml:依賴配置文件

導入pom依賴

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

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

第一個:springboot依賴
第二個:mybatis
第三個:數(shù)據(jù)庫驅動依賴
第四個: 阿里巴巴數(shù)據(jù)庫連接池

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ù)庫驅動 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 數(shù)據(jù)庫連接池 -->
        <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)

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

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

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

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

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

數(shù)據(jù)庫validationQuery驗證語句
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

這個驗證連接語句需要根據(jù)自己連的數(shù)據(jù)庫進行更改配置語句

編寫resource的mapper查詢

在resource/mapper里,我創(chuàng)建了兩個文件MyDb1Mapper.xmlMyDb2Mapper.xml,用來標識兩個不同數(shù)據(jù)庫的連接的文件.
其中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ù)庫接口文件路徑

編寫mapper接口

在com.demo.mapper下有兩個文件夾,分別標識不同的數(shù)據(jù)庫接口文件,
其中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ù)庫配置

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

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

其中,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的代碼有一個很重要的區(qū)別,必須有且只有一個數(shù)據(jù)庫作為主數(shù)據(jù)庫。
用注解@primary標注
可以仔細看MyDb1Config和MyDb2Config的這個區(qū)別,他們的區(qū)別就在于@primary

啟動類

Application.java啟動類代碼如下:

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

運行成功截圖

在這里插入圖片描述

在這里插入圖片描述

異常處理

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

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

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

結語

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

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

相關文章

最新評論