springboot整合postgres

开发环境:windows10、jdk-13.0.1、apache-maven-3.6.2、PostgreSQL 12、Intellij IDEA2019.2.4

postgres官网:https://www.postgresql.org/

一、创建maven项目my-springboot-template,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>com.zsx</groupId>
    <artifactId>my-springboot-template</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>13</java.version>
        <jaxb-impl.version>2.3.2</jaxb-impl.version>
        <jaxb-core.version>2.3.0.1</jaxb-core.version>
        <postgresql.version>42.2.8</postgresql.version>
        <fastjson.version>1.2.62</fastjson.version>
        <lombok.version>1.18.10</lombok.version>
        <mybatis.version>2.1.1</mybatis.version>
        <guava.version>28.1-jre</guava.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- java11中没有该类jar包,需引入 -->
        <dependency>
            <groupId>org.glassfish.jaxb</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>${jaxb-core.version}</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>${jaxb-impl.version}</version>
        </dependency>
        <!-- postgres-->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>${postgresql.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- guava -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>${guava.version}</version>
        </dependency>
        <!-- junit5运行所需jar包 -->
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
            <!--<version>${junit-jupiter.version}</version>-->
        </dependency>
        <!-- 引入热部署 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.zsx.MySpringbootTemplateApplication</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>13</source>
                    <target>13</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <!-- 打包时所包含的文件 -->
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

二、application.yml中配置数据库

spring:
  application:
    name: postgres
  datasource:
    username: postgres
    password: 1234
    url: jdbc:postgresql://127.0.0.1:5432/mydb10
    driver-class-name: org.postgresql.Driver
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      maximum-pool-size: 20
      max-lifetime: 1800000
      idle-timeout: 30000
      data-source-properties:
        prepStmtCacheSize: 250
        prepStmtCacheSqlLimit: 2048
        cachePrepStmts: true
        useServerPrepStmts: true

三、程序引导类

package com.zsx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MySpringbootTemplateApplication {

    public static void main(String[] args) {
        SpringApplication.run(MySpringbootTemplateApplication.class, args);
    }
}

四、编写测试类

package com.zsx;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.util.Map;
import java.util.UUID;

@SpringBootTest
@ExtendWith(SpringExtension.class)
public class PostgresJdbcTemplateTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    void create() {
        String sqlDropDatabase = "DROP DATABASE IF EXISTS my_schema ";
        jdbcTemplate.execute(sqlDropDatabase);
        String sqlDatabase = "CREATE DATABASE my_schema";
        jdbcTemplate.execute(sqlDatabase);
        String sqlDrop = "DROP SCHEMA IF EXISTS my_schema CASCADE";
        jdbcTemplate.execute(sqlDrop);
        String sqlSchema = "CREATE schema my_schema";
        jdbcTemplate.execute(sqlSchema);
        String sqlTable = "CREATE TABLE my_schema.t_test(\"test_id\" varchar(64), \"test_json\" jsonb)";
        jdbcTemplate.execute(sqlTable);
    }

    @Test
    void insert() {
        String sql = "INSERT INTO my_schema.t_test VALUES (?, ?::jsonb)";
        // 不可变Map
        Map<String, String> personMap = ImmutableMap.<String, String> builder()
                .put("personId", "126")
                .put("name", "Tom")
                .put("age", "22")
                .put("createTime", "2019-11-02 22:09:23")
                .build();
        jdbcTemplate.update(sql, new Object[] {UUID.randomUUID().toString(), JSON.toJSONString(personMap)});
//        String id = "4495bf53-3cf9-4048-b97e-c1505f7748c0";
//        jdbcTemplate.update(sql, new Object[] {id, JSON.toJSONString(personMap)});
    }

    @Test
    void update() {
        String sql = "UPDATE my_schema.t_test SET test_json = ?::jsonb WHERE test_id = ?";
        // 不可变Map
        Map<String, String> personMap = ImmutableMap.<String, String> builder()
                .put("personId", "128")
                .put("name", "Tom1")
                .put("age", "20")
                .put("createTime", "2019-11-02 22:10:11")
                .build();
        String id = "4495bf53-3cf9-4048-b97e-c1505f7748c0";
        jdbcTemplate.update(sql, new Object[] {JSON.toJSONString(personMap), id});
    }

    @Test
    void delete() {
        String sql = "DELETE FROM my_schema.t_test WHERE test_json ::jsonb->>'age' = ? ";
        jdbcTemplate.update(sql, new Object[] {"22"});
    }
}

五、运行测试方法create()

23:29:10.540 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
23:29:10.563 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
23:29:10.612 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.zsx.PostgresJdbcTemplateTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
23:29:10.632 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.zsx.PostgresJdbcTemplateTest], using SpringBootContextLoader
23:29:10.643 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.zsx.PostgresJdbcTemplateTest]: class path resource [com/zsx/PostgresJdbcTemplateTest-context.xml] does not exist
23:29:10.643 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.zsx.PostgresJdbcTemplateTest]: class path resource [com/zsx/PostgresJdbcTemplateTestContext.groovy] does not exist
23:29:10.644 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.zsx.PostgresJdbcTemplateTest]: no resource found for suffixes {-context.xml, Context.groovy}.
23:29:10.645 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.zsx.PostgresJdbcTemplateTest]: PostgresJdbcTemplateTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
23:29:10.713 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.zsx.PostgresJdbcTemplateTest]
23:29:10.812 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [F:\IdeaProjects\myspringboottemplate\target\classes\com\zsx\MySpringbootTemplateApplication.class]
23:29:10.813 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.zsx.MySpringbootTemplateApplication for test class com.zsx.PostgresJdbcTemplateTest
23:29:10.956 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.zsx.PostgresJdbcTemplateTest]: using defaults.
23:29:10.957 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
23:29:10.974 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@67b9b51a, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@1205bd62, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@7ef27d7f, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@490caf5f, org.springframework.test.context.support.DirtiesContextTestExecutionListener@6337c201, org.springframework.test.context.transaction.TransactionalTestExecutionListener@5c669da8, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@31920ade, org.springframework.test.context.event.EventPublishingTestExecutionListener@1d483de4, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@4032d386, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@28d18df5, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@934b6cb, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@55cf0d14, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@3b74ac8]
23:29:10.981 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@27d5a580 testClass = PostgresJdbcTemplateTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@198d6542 testClass = PostgresJdbcTemplateTest, locations = '{}', classes = '{class com.zsx.MySpringbootTemplateApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3c947bc5, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@1356d4d4, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@1bb266b3, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@68c72235], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
23:29:11.032 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.0.RELEASE)

2019-11-02 23:29:11.572  INFO 12236 --- [           main] com.zsx.PostgresJdbcTemplateTest         : Starting PostgresJdbcTemplateTest on zsx with PID 12236 (started by admin in F:\IdeaProjects\myspringboottemplate)
2019-11-02 23:29:11.573  INFO 12236 --- [           main] com.zsx.PostgresJdbcTemplateTest         : No active profile set, falling back to default profiles: default
2019-11-02 23:29:12.889  WARN 12236 --- [           main] o.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in '[com.zsx]' package. Please check your configuration.
2019-11-02 23:29:13.987  INFO 12236 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-11-02 23:29:15.225  WARN 12236 --- [           main] com.zaxxer.hikari.HikariConfig           : HikariPool-1 - idleTimeout has been set but has no effect because the pool is operating as a fixed size pool.
2019-11-02 23:29:15.227  INFO 12236 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-11-02 23:29:15.545  INFO 12236 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-11-02 23:29:16.375  INFO 12236 --- [           main] com.zsx.PostgresJdbcTemplateTest         : Started PostgresJdbcTemplateTest in 5.327 seconds (JVM running for 6.801)


2019-11-02 23:29:18.128  INFO 12236 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2019-11-02 23:29:18.310  INFO 12236 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2019-11-02 23:29:18.311  INFO 12236 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code 0

从以上结果可以看出springboot整合postgres成功

发布了129 篇原创文章 · 获赞 14 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/zsx18273117003/article/details/102875233