【问题标题】:Create Postgres database if it doesn't exist when running spring boot application如果运行 Spring Boot 应用程序时不存在,则创建 Postgres 数据库
【发布时间】:2018-12-12 21:30:32
【问题描述】:

我正在使用PostgreSQLspring-boot-2.0.1 并希望我的应用程序在数据库不存在时创建它。 我的application.properties中有以下选项

spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL94Dialect

spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=123

上面我得到了错误:

Caused by: org.postgresql.util.PSQLException: FATAL: database "mydb" does not exist

知道我错过了什么吗?

【问题讨论】:

  • generate-ddl 配置只作用于表而不作用于数据库;如果数据库不存在,则不会创建

标签: spring postgresql spring-boot spring-data


【解决方案1】:

如果数据库不存在,您可以使用spring boot 创建数据库。至少对于 MySQL,我们这样做:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb?createDatabaseIfNotExist=true

所以应该和PostgreSQL一样:

spring.datasource.url= jdbc:postgresql://localhost:5432/mydb?createDatabaseIfNotExist=true

【讨论】:

  • 感谢您的回答,但这不适用于 postgres。它只适用于 mysql
  • 如前所述,此解决方案不适用于 Postgres。
【解决方案2】:

由于所有 Postgres 安装都带有一个默认数据库,从技术上讲,它应该可以在一开始(当应用程序启动时)连接到它,然后调用

CREATE DATABASE

这是您可以在 spring 初始化之前以编程方式执行的操作,但在读取属性之后,例如在 Environment Post Processor

之所以需要这么早调用,是因为一方面您可能想利用 spring boot 读取的属性,但到时候 spring boot bean 将开始获取处于“运行”状态的新创建的数据库.

所以,从技术上讲,它是可能的。但是,我看不到这种场景的真实用例。 如果是用于测试,那么您可以完美地使用问题开头提到的默认 Postgres 数据库。

如果是用于生产环境 - 通常 DBA 不会允许这样做,因为为了能够运行 CREATE DATABASE 语句,连接到 Postgres(在这种情况下为 Spring Boot 应用程序)的用户应该有一个非常“ strong”createdb 特权,这是 DBA 并不想真正分享的东西。

【讨论】:

    【解决方案3】:

    简答:

    不能像我们在MySQL那样做,你需要想办法 用Spring Configuration自己做吧

    【讨论】:

      猜你喜欢
      • 2016-10-24
      • 2016-04-27
      • 2013-03-26
      • 2019-03-06
      • 1970-01-01
      • 2019-09-02
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多