我正在使用PostgreSQL
和spring-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
知道我错过了什么吗?
5条答案
按热度按时间8yparm6h1#
由于所有Postgres安装都带有一个默认数据库,因此从技术上讲,应该可以在一开始(当应用程序启动时)连接到它,然后调用
CREATE DATABASE
这是您可以在spring初始化之前,但在读取属性之后,例如在Environment Post Processor中,通过编程方式完成的事情
之所以需要这么早的调用,是因为一方面您可能希望利用spring Boot 读取的属性,但到spring boot beans开始获取处于“操作”状态的新创建的数据库时。
所以,从技术上讲是可能的。但是,我看不到这种情况的真实的用例。如果是测试,那么你可以完美地使用默认的Postgres数据库,这在问题的开头就提到了。
如果是用于生产环境-通常DBA不会允许这样做,因为为了能够运行
CREATE DATABASE
语句,连接到Postgres(在本例中为spring Boot 应用程序)的用户应该具有非常“强”的 createdb 特权,DBA不会真正想要共享这些特权。628mspwn2#
如果
spring boot
不存在数据库,您可以创建数据库。至少在MySQL中,我们可以:所以PostgreSQL应该是一样的:
这不适用于PostgreSQL。
cwxwcias3#
**Sping Boot **
Postgres不支持
createDatabaseIfNotExist=true
,所以你可以尝试类似的方法,它为我工作,见Screenshotpn9klfpd4#
简答:
它不能像我们在
MySQL
中所做的那样完成,您需要在Spring Configuration
之外找到一种自己完成的方法hgncfbus5#
一个解决方案是添加创建数据库的脚本......即使,你在postgres中没有“if not exist”。下面是我如何用docker文件解决这个问题的,但我想你可以在postgres中做一个sql脚本。我把这个放在www.example.com中initdb.sh......