返回

Docker 中 H2 驱动 Quarkus 应用报错“找不到默认数据源”的解决方法

java

在 Docker 中使用 H2 运行 Quarkus 应用程序

问题:找不到默认数据源

在使用 ./run/run.sh -dc 命令在 Docker 中运行 Quarkus 应用程序时,可能会遇到以下错误:

Model classes are defined for the default persistence unit <default> but configured datasource <default> not found: the default EntityManagerFactory will not be created. To solve this, configure the default datasource. Refer to https://quarkus.io/guides/datasource for guidance.

解决方案

1. 检查数据源配置

  • 确保 quarkus.datasource.db-kind 设置为 h2
  • 检查 quarkus.datasource.jdbc.url 是否是正确的 H2 数据库 URL。

2. 检查依赖项

  • 确保 pom.xml 文件中包含 quarkus-jdbc-h2 依赖项。

3. 配置默认数据源

  • application.properties 文件中,添加以下配置:
quarkus.datasource.default=h2

其他提示

  • 移除 INIT=RUNSCRIPT FROM 'classpath:scripts/carga_banco_dados.sql' 部分不是解决错误的原因。
  • 确保在 Docker 中使用与本地相同的配置。

示例代码

# application.properties

quarkus.datasource.db-kind=h2
quarkus.datasource.jdbc.url=jdbc:h2:mem:exemplo
quarkus.datasource.username=username
quarkus.datasource.password=password
quarkus.datasource.default=h2

常见问题解答

1. 为什么需要配置默认数据源?

默认情况下,Quarkus 不会创建一个 EntityManagerFactory,除非有明确配置的数据源。

2. 如何在本地运行时避免此错误?

在 "dev" 配置文件中,Quarkus 会自动创建一个名为 "test" 的默认数据源。

3. 可以使用其他数据库吗?

是的,Quarkus 支持各种数据库,包括 MySQL、PostgreSQL 和 Oracle。

4. 如何调试此问题?

检查日志和堆栈跟踪以了解有关错误的更多信息。

5. 此解决方案是否适用于所有 Quarkus 版本?

该解决方案适用于 Quarkus 2.7.6,但可能需要针对其他版本进行调整。