SpringBoot+数据库配置 Oracle/MySQL/PostgreSQL

1. SpringBoot 配置连接mysql数据库

添加依赖
<!-- mysql驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>

在application.properties 文件 添加配置

#数据库连接信息
spring.datasource.url=jdbc:mysql://localhost:3306/boot_transaction?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.database=mysql

 

2. SpringBoot 配置连接Oracle数据库 

添加依赖

<dependency>
    <groupId>com.oracle.database.jdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <version>21.1.0.0</version>
</dependency>

在application.properties 文件 添加配置

#spring.datasource.url=jdbc:oracle:thin:@//主机名:端口号/服务名
spring.datasource.url=jdbc:oracle:thin:@//Host Name:port/Service Name
spring.datasource.username=username
spring.datasource.password=pwd
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect

  

3. SpringBoot 配置连接PostgreSQL数据库

添加依赖

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.2.20</version>
</dependency>

在application.properties 文件 添加配置

#postgresql
spring.datasource.url=jdbc:postgresql://serverip:port/yourdatabasename?currentSchema=yourschemaname
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

 

引入数据库配置

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DataSourceConfig {

    @Value("${spring.datasource.url}")
    String jdbcUrl;

    @Value("${spring.datasource.username}")
    String username;

    @Value("${spring.datasource.password}")
    String password;

    @Bean
    public DataSource getDataSource() throws Exception {
        DataSourceBuilder<?> dataSourceBuilder = DataSourceBuilder.create();

        dataSourceBuilder.url(jdbcUrl);
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);

        return dataSourceBuilder.build();
    }
}

 

posted on 2021-10-12 18:27  dreamstar  阅读(1630)  评论(0编辑  收藏  举报