gpt4 book ai didi

java - 在 hibernate 启动之前创建数据库(例如 Flyway 或其他)

转载 作者:行者123 更新时间:2023-11-29 12:28:04 26 4
gpt4 key购买 nike

我正在使用 Spring 和 Hibernate,我想在 hibernate 启动之前创建一个数据库,否则我会收到 Caused by: org.postgresql.util.PSQLException: FATAL: database "db"does not exist.

我的属性文件中有这个:

spring.datasource.url=jdbc:postgresql://postgres:5432/db
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
server.port=3001

db 在 postgres 数据库中不存在,因此抛出异常。

有人说我可以用Flyway:

Create PostgreSQL database on the fly using Hibernate even if the DB doesn't exist

还有人说不可能:

How to create a database with flyway?

如何使用flyway完成数据库的创建?
或者,如果它仅用于创建后的迁移,我该如何创建之前运行的初始化 bean(你能告诉我一些代码),如此处接受的答案中所述:

Create PostgreSQL database on the fly using Hibernate even if the DB doesn't exist

然后开始使用 flyway 进行迁移(第一个表等)...

之后我可以将 ddl-auto 切换为 none。

流程是什么?

最佳答案

Spring 支持在启动时执行 flyway 和/或 liquibase (是的,甚至在您的 ORM 层尝试连接到它之前):

To automatically run Flyway database migrations on startup, add the org.flywaydb:flyway-core to your classpath.

The migrations are scripts in the form V[VERSION]__[NAME].sql (with an underscore-separated version, such as ‘1’ or ‘2_1’). By default, they are in a folder called classpath:db/migration, but you can modify that location by setting spring.flyway.locations. This is a comma-separated list of one or more classpath: or filesystem: locations. For example, the following configuration would search for scripts in both the default classpath location and the /opt/migration directory

来源:

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-execute-flyway-database-migrations-on-startup

请阅读手册。

另外:您(当然)甚至可以执行像CREATE DATABASE 这样的语句,您只需要一个单独的连接即可:How to create a database with flyway?

一些 JDBC 驱动程序甚至允许完全跳过该步骤:https://stackoverflow.com/a/34379819/351861

关于java - 在 hibernate 启动之前创建数据库(例如 Flyway 或其他),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55918839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com