java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot配置postgresql数据库

SpringBoot项目配置postgresql数据库完整步骤(配置多数据源)

作者:昊阳呀

PostgreSQL是一种特性非常齐全的自由软件的对象-关系型数据库管理系统(ORDBMS),下面这篇文章主要给大家介绍了关于SpringBoot项目配置postgresql数据库(配置多数据源)的相关资料,需要的朋友可以参考下

pg库也是常用的数据库之一,有些刚开始接触开发的老师可能不熟,这里简单介绍一下,总体使用方法和mysql类似,所以这里只讲配置方法

pom文件导入依赖

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </dependency>        
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.18</version>
        </dependency>

yml文件配置(多数据源):

spring:
  datasource:
    bd3:
      jdbc-url: jdbc:postgresql://XXX.XXX.XX.XXX:5432/test1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&allowMultiQueries=true
      username: XXX
      password: XXX
      driver-class-name: org.postgresql.Driver
      type: com.zaxxer.hikari.HikariDataSource
      hikari:
        minimum-idle: 3
        auto-commit: true
        idle-timeout: 10000
        pool-name: DatebookHikariCP
        max-lifetime: 1800000
        connection-timeout: 30000
    timed:
      jdbc-url: jdbc:postgresql://XXX.XXX.XX.XXX:5432/test2?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&allowMultiQueries=true
      username: XXX
      password: XXX
      driver-class-name: org.postgresql.Driver
      type: com.zaxxer.hikari.HikariDataSource
      hikari:
        minimum-idle: 3
        auto-commit: true
        idle-timeout: 10000
        pool-name: DatebookHikariCP
        max-lifetime: 1800000
        connection-timeout: 30000

这个地方test1是数据库1,test2是数据库2,yml文件一定要主要好格式,建议用properties

下面是有关于多数据源的配置

文件夹格式,这里直接放贴图

不同数据源的dao层要放到对应文件夹下

下面是数据源的配置文件

MyBaitsSqlSessionFactory配置文件

package com.XXX.XXX.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
public class MyBaitsSqlSessionFactory {
    private MyBaitsSqlSessionFactory() {
    }
    private static final MyBaitsSqlSessionFactory onlyOne = new MyBaitsSqlSessionFactory();
    public static MyBaitsSqlSessionFactory getInstance() {
        return onlyOne;
    }
    public SqlSessionFactory sessionFactory(DataSource dataSource, String mapper_location, String type_aliases_package, boolean mapUnderscoreToCamelCase) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setVfs(SpringBootVFS.class);
        //mybatis扫描xml所在位置
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper_location));
        //实体类位置
        bean.setTypeAliasesPackage(type_aliases_package);
        //mybatis配置
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(mapUnderscoreToCamelCase);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }
}

Bd3Config配置文件

package com.XXX.XXX.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@SpringBootConfiguration
@MapperScan(basePackages = "com.XXX.XXX.dao.bd3", sqlSessionFactoryRef = "bd3SessionFactory", sqlSessionTemplateRef = "bd3SqlSessionTemplate")
public class Bd3Config {
    //@Value("${mybatis.mapper-locations}")
    private String mapper_location = "classpath*:/mapper/bd3/**/*.xml";
    @Value("${mybatis.type-aliases-package}")
    private String type_aliases_package;
    @Value("${mybatis.configuration.map-underscore-to-camel-case}")
    private boolean mapUnderscoreToCamelCase;
    /**
     * 初始化连接池
     *
     * @return DataSource
     */
    @Bean(name = "bd3")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.bd3")
    public DataSource bd3DataSource() {
        return DataSourceBuilder.create().build();
    }
    /**
     * 构建 SqlSessionFactory
     *
     * @return SqlSessionFactory
     */
    @Bean(name = "bd3SessionFactory")
    @Primary
    public SqlSessionFactory bd3SessionFactory() throws Exception {
        MyBaitsSqlSessionFactory myBatisFactory = MyBaitsSqlSessionFactory.getInstance();
        return myBatisFactory.sessionFactory(bd3DataSource(), mapper_location, type_aliases_package, mapUnderscoreToCamelCase);
    }
    /*
     * 配置事物
     *
     * @return DataSourceTransactionManager
     */
    @Bean("bd3TransactionManager")
    @Primary
    public DataSourceTransactionManager TransactionManager() {
        return new DataSourceTransactionManager(bd3DataSource());
    }
    /**
     * 构建 SqlSessionTemplate
     *
     * @return SqlSessionTemplate
     */
    @Bean(name = "bd3SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(bd3SessionFactory());
    }
}

TimedConfig配置文件

package com.XXX.XXX.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@SpringBootConfiguration
@MapperScan(basePackages = "com.XX.XXX.dao.timed", sqlSessionFactoryRef = "timedSessionFactory", sqlSessionTemplateRef = "timedSqlSessionTemplate")
public class TimedConfig {
    //@Value("${mybatis.mapper-locations}")
    private String mapper_location = "classpath*:/mapper/timed/**/*.xml";
    @Value("${mybatis.type-aliases-package}")
    private String type_aliases_package;
    @Value("${mybatis.configuration.map-underscore-to-camel-case}")
    private boolean mapUnderscoreToCamelCase;
    /**
     * 初始化连接池
     *
     * @return DataSource
     */
    @Bean(name = "timed")
    @ConfigurationProperties(prefix = "spring.datasource.timed")
    public DataSource timedDataSource() {
        return DataSourceBuilder.create().build();
    }
    /**
     * 构建 SqlSessionFactory
     *
     * @return SqlSessionFactory
     */
    @Bean(name = "timedSessionFactory")
    public SqlSessionFactory timedSessionFactory() throws Exception {
        MyBaitsSqlSessionFactory myBatisFactory = MyBaitsSqlSessionFactory.getInstance();
        return myBatisFactory.sessionFactory(timedDataSource(), mapper_location, type_aliases_package, mapUnderscoreToCamelCase);
    }
    /*
     * 配置事物
     *
     * @return DataSourceTransactionManager
     */
    @Bean("timedTransactionManager")
    public DataSourceTransactionManager TransactionManager() {
        return new DataSourceTransactionManager(timedDataSource());
    }
    /**
     * 构建 SqlSessionTemplate
     *
     * @return SqlSessionTemplate
     */
    @Bean(name = "timedSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(timedSessionFactory());
    }
}

然后就可以正常使用了,希望大家技术越来越好!

总结

到此这篇关于SpringBoot项目配置postgresql数据库(配置多数据源)的文章就介绍到这了,更多相关SpringBoot配置postgresql数据库内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文