springboot对接postgres

安装postgres

注意:下述链接方式会自动创建数据库steven_russell,若需要创建其他数据库,可以手动执行命令创建数据库

docker run --name postgres \

-p 5432:5432 \

-e POSTGRES_USER=steven_russell \

-e POSTGRES_PASSWORD=123456 \

-itd --privileged=true postgres

docker安装postgres_Steven-Russell的博客-CSDN博客

创建springBoot项目

搭建最简单的SpringBoot项目_Steven-Russell的博客-CSDN博客

引入postgres依赖

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

编辑resource配置文件

注意:需要配置方言

spring:
  datasource:
    url: jdbc:postgresql://192.168.30.128:5432/steven_russell
    username: steven_russell
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    database-platform: org.hibernate.dialect.PostgresPlusDialect

创建实体

@Data
@Entity
@Table(name = "tbl_user")
public class User {

    @Id
    @Column
    @GeneratedValue
    private int id;

    @Column
    private String name;

    @Column
    private String addr;

    @UpdateTimestamp
    @Column
    private Date updateTime;
}

创建repository

创建controller

@RestController
@RequestMapping(value = "postgres")
public class PostgresController {

    private final UserRepository userRepository;

    public PostgresController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @PostMapping(value = "add")
    public String addUser(String name) {
        User user = new User();
        user.setName(name);
        user.setAddr("chongqing");
        userRepository.save(user);
        return userRepository.findAllByName(name).toString();
    }

}

测试