ZetCode

Spring Boot PostgreSQL

最后修改于 2023 年 8 月 2 日

在本文中,我们将展示如何在 Spring Boot 应用程序中使用 PostgreSQL 数据库。

Spring 是一个流行的 Java 应用程序框架,用于创建企业应用程序。Spring Boot 是 Spring 框架的演进,它有助于以最小的 effort 创建基于 Spring 的独立、生产级应用程序。

PostgreSQL

PostgreSQL 是一个功能强大的开源对象关系数据库系统。它是一个多用户数据库管理系统。它可以在多种平台上运行,包括 Linux、FreeBSD、Solaris、Microsoft Windows 和 Mac OS X。PostgreSQL 由 PostgreSQL 全球开发小组开发。

PostgreSQL 设置

我们将展示如何在 Debian Linux 系统上安装 PostgreSQL 数据库。

$ sudo apt-get install postgresql

此命令安装 PostgreSQL 服务器和相关软件包。

$ /etc/init.d/postgresql status

我们使用 postgresql status 命令检查数据库的状态。

$ sudo -u postgres psql postgres
psql (9.5.10)
Type "help" for help.

postgres=# \password postgres
Enter new password:
Enter it again:

安装后,将创建一个具有管理权限的 postgres 用户,并带有空的默认密码。作为第一步,我们需要为 postgres 设置密码。

$ sudo -u postgres createuser --interactive --password user12
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) n
Password:

我们创建一个新的数据库用户。

$ sudo -u postgres createdb testdb -O user12

我们使用 createdb 命令创建一个新的 testdb 数据库,该数据库将由 user12 拥有。

$ sudo vi /etc/postgresql/9.5/main/pg_hba.conf

我们编辑 pg_hba.conf 文件。

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

为了能够在本地 PostgreSQL 安装中运行 Spring Boot 应用程序,我们将 Unix 域套接字和本地连接的身份验证方法更改为 trust

$ sudo service postgresql restart

我们重启 PostgreSQL 以启用更改。

$ psql -U user12 -d testdb -W
Password for user user12:
psql (9.5.10)
Type "help" for help.

testdb=>

现在我们可以使用 psql 工具连接到数据库。

Spring Boot PostgreSQL 示例

以下应用程序是一个简单的 Spring Boot Web 应用程序,它使用 PostgreSQL 数据库。我们有一个主页,其中包含一个链接,用于显示来自数据库表的数据。我们使用 Thymeleaf 模板系统将数据与 HTML 连接起来。

build.gradle 
...
src
├── main
│  ├── java
│  │  └── com
│  │      └── zetcode
│  │          ├── Application.java
│  │          ├── controller
│  │          │  └── MyController.java
│  │          ├── model
│  │          │  └── City.java
│  │          ├── repository
│  │          │  └── CityRepository.java
│  │          └── service
│  │              ├── CityService.java
│  │              └── ICityService.java
│  └── resources
│      ├── application.properties
│      ├── data-postgres.sql
│      ├── schema-postgres.sql
│      ├── static
│      │  └── index.html
│      └── templates
│          └── showCities.html
└── test
    ├── java
    └── resources

这是项目结构。

build.gradle
plugins {
    id 'java'
    id 'org.springframework.boot' version '3.1.1'
    id 'io.spring.dependency-management' version '1.1.0'
}

group = 'com.zetcode'
version = '0.0.1-SNAPSHOT'

java {
    sourceCompatibility = '17'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.postgresql:postgresql:42.6.0'
}

Spring Boot 启动器是一组方便的依赖描述符,它们大大简化了配置。 spring-boot-starter-web 是一个用于构建 Web 应用程序(包括 RESTful 应用程序)的启动器,它使用 Spring MVC。它使用 Tomcat 作为默认的嵌入式容器。

spring-boot-starter-thymeleaf 是一个用于使用 Thymeleaf 视图构建 MVC Web 应用程序的启动器。 spring-boot-starter-data-jpa 是一个用于将 Spring Data JPA 与 Hibernate 结合使用的启动器。

postgresql 依赖项用于 PostgreSQL 数据库驱动程序。

resources/application.properties
spring.main.banner-mode=off
logging.level.org.springframework=ERROR

spring.jpa.hibernate.ddl-auto=none

spring.datasource.url=jdbc:postgresql://:5432/testdb
spring.datasource.username=postgres
spring.datasource.password=s$cret

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

application.properties 文件中,我们编写了 Spring Boot 应用程序的各种配置设置。

使用 spring.main.banner-mode 属性,我们关闭 Spring 标语。为了避免冲突,我们使用 spring.jpa.hibernate.ddl-auto=none 关闭自动模式创建。

在 Spring 数据源属性中,我们设置 PostgreSQL 数据源。

设置 spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation 选项是为了避免最近的问题。如果没有此选项,我们会得到以下错误

java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc.PgConnection.createClob()
is not yet implemented.
com/zetcode/model/City.java
package com.zetcode.model;

import java.util.Objects;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "cities")
public class City {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private int population;

    public City() {
    }

    public City(Long id, String name, int population) {

        this.id = id;
        this.name = name;
        this.population = population;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 79 * hash + Objects.hashCode(this.id);
        hash = 79 * hash + Objects.hashCode(this.name);
        hash = 79 * hash + this.population;
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final City other = (City) obj;
        if (this.population != other.population) {
            return false;
        }
        if (!Objects.equals(this.name, other.name)) {
            return false;
        }
        return Objects.equals(this.id, other.id);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("City{");
        sb.append("id=").append(id);
        sb.append(", name='").append(name).append('\'');
        sb.append(", population=").append(population);
        sb.append('}');
        return sb.toString();
    }
}

这是 City 实体。每个实体都必须至少定义两个注解:@Entity@Id

@Entity
@Table(name = "cities")
public class City {

@Entity 注解指定该类是一个实体,并映射到一个数据库表。@Table 注解指定用于映射的数据库表的名称。

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Id 注解指定了实体的标识符,@GeneratedValue 提供了为主键值生成策略的规范。

resources/schema-postgres.sql
DROP TABLE IF EXISTS cities;
CREATE TABLE cities(id serial PRIMARY KEY, name VARCHAR(255), population integer);

当应用程序启动时,将执行 schema-postgres.sql 脚本,前提是关闭了自动模式创建。该脚本将创建一个新的数据库表。

resources/data-postgres.sql
INSERT INTO cities(name, population) VALUES('Bratislava', 432000);
INSERT INTO cities(name, population) VALUES('Budapest', 1759000);
INSERT INTO cities(name, population) VALUES('Prague', 1280000);
INSERT INTO cities(name, population) VALUES('Warsaw', 1748000);
INSERT INTO cities(name, population) VALUES('Los Angeles', 3971000);
INSERT INTO cities(name, population) VALUES('New York', 8550000);
INSERT INTO cities(name, population) VALUES('Edinburgh', 464000);
INSERT INTO cities(name, population) VALUES('Berlin', 3671000);

稍后,将执行 data-postgres.sql 文件,以用数据填充表。

com/zetcode/repository/CityRepository.java
package com.zetcode.repository;

import com.zetcode.model.City;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CityRepository extends CrudRepository<City, Long> {

}

通过扩展 Spring CrudRepository,我们将为我们的数据存储库实现一些方法,包括 findAll。通过这种方式,我们节省了大量的样板代码。

com/zetcode/service/ICityService.java
package com.zetcode.service;

import com.zetcode.model.City;

import java.util.List;

public interface ICityService {

    List<City> findAll();
}

ICityService 提供了一个契约方法,用于从数据源获取所有城市。

com/zetcode/service/CityService.java
package com.zetcode.service;

import com.zetcode.model.City;
import com.zetcode.repository.CityRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CityService implements ICityService {

    private final CityRepository repository;

    @Autowired
    public CityService(CityRepository repository) {
        this.repository = repository;
    }

    @Override
    public List<City> findAll() {

        return (List<City>) repository.findAll();
    }
}

CityService 包含 findAll 方法的实现。 我们使用存储库从数据库检索数据。

@Autowired
public CityService(CityRepository repository) {
    this.repository = repository;
}

CityRepository 被注入。

return (List<City>) repository.findAll();

存储库的 findAll 方法返回城市列表。

com/zetcode/MyController.java
package com.zetcode.controller;

import com.zetcode.model.City;
import com.zetcode.service.ICityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class MyController {

    private final ICityService cityService;

    @Autowired
    public MyController(ICityService cityService) {
        this.cityService = cityService;
    }

    @GetMapping("/showCities")
    public String findCities(Model model) {

        var cities = (List<City>) cityService.findAll();

        model.addAttribute("cities", cities);

        return "showCities";
    }
}

MyController 包含一个映射。

private final ICityService cityService;

@Autowired
public MyController(ICityService cityService) {
    this.cityService = cityService;
}

我们将 ICityService 注入到 cityService 字段中。

@GetMapping("/showCities")
public String findCities(Model model) {

    var cities = (List<City>) cityService.findAll();

    model.addAttribute("cities", cities);

    return "showCities";
}

我们将路径为 showCities 的请求映射到控制器的 findCities 方法。默认请求是 GET 请求。模型获得一个城市列表,并将处理发送到 showCities.html Thymeleaf 模板文件。

resources/templates/showCities.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Cities</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <body>
        <h2>List of cities</h2>

        <table>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Population</th>
            </tr>

            <tr th:each="city : ${cities}">
                <td th:text="${city.id}">Id</td>
                <td th:text="${city.name}">Name</td>
                <td th:text="${city.population}">Population</td>
            </tr>
        </table>

    </body>
</html>

showCities.html 模板文件中,我们在 HTML 表中显示数据。

resources/static/index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="showCities">Show cities</a>
    </body>
</html>

index.html 中,有一个链接用于显示所有城市。

com/zetcode/Application.java
package com.zetcode;

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

@SpringBootApplication
public class Application {

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

Application 设置了 Spring Boot 应用程序。@SpringBootApplication 启用了自动配置和组件扫描。

$ ./gradlew bootRun

运行应用程序后,我们可以导航到 localhost:8080

在本文中,我们展示了如何在 Spring Boot 应用程序中使用 PostgreSQL 数据库。

作者

我叫 Jan Bodnar,是一个充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我撰写了 1400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 Spring Boot 教程