配置Micronaut使用PostgreSQL替代MySQL及问题排查
Micronaut切换PostgreSQL的配置问题解决
问题1:URL占位符解析错误
出现${auto.test.resources.jpa.default.properties.hibernate.connection.url}无法解析,是因为Micronaut Test Resources对PostgreSQL的自动配置需要匹配正确的依赖和配置项,无需手动指定URL,按以下步骤调整:
- 确保
build.gradle中添加PostgreSQL驱动和Test Resources的PostgreSQL支持依赖:
dependencies { // PostgreSQL驱动 runtimeOnly 'org.postgresql:postgresql:42.6.0' // Test Resources PostgreSQL自动容器支持 testImplementation 'io.micronaut.testresources:micronaut-testresources-postgresql' // 若使用Hibernate Reactive,补充对应依赖 implementation 'io.micronaut.sql:micronaut-hibernate-reactive-jpa' runtimeOnly 'io.vertx:vertx-pg-client' }
application.yml中配置PostgreSQL,依赖Test Resources自动注入连接参数:
datasources: default: url: ${db.url} driverClassName: org.postgresql.Driver username: ${db.username} password: ${db.password} jpa: default: entity-scan: packages: "你的实体类包路径" properties: hibernate: hbm2ddl: auto: update show_sql: true format_sql: true
Micronaut Test Resources会自动启动PostgreSQL容器,并填充db.url、db.username、db.password这些占位符,无需手动配置容器和连接地址。
问题2:NoClassDefFoundError: com/ongres/scram/common/stringprep/StringPreparation
该错误是因为PostgreSQL的SCRAM认证需要额外依赖,在build.gradle中添加以下依赖即可解决:
dependencies { // 新增SCRAM认证依赖 runtimeOnly 'com.ongres.scram:scram-client:2.1' }
完整配置示例
build.gradle(Groovy)
plugins { id("io.micronaut.application") version "4.0.0" id("java") } version "0.1" group "你的项目组名" repositories { mavenCentral() } dependencies { implementation("io.micronaut:micronaut-validation") implementation("io.micronaut.sql:micronaut-hibernate-reactive-jpa") runtimeOnly("org.postgresql:postgresql:42.6.0") runtimeOnly("io.vertx:vertx-pg-client") runtimeOnly("com.ongres.scram:scram-client:2.1") testImplementation("io.micronaut.testresources:micronaut-testresources-postgresql") testImplementation("io.micronaut.test:micronaut-test-junit5") } micronaut { runtime("netty") testRuntime("junit5") processing { incremental(true) annotations("你的项目组名.*") } }
application.yml
micronaut: application: name: 你的应用名 datasources: default: url: ${db.url} driverClassName: org.postgresql.Driver username: ${db.username} password: ${db.password} dialect: POSTGRES jpa: default: entity-scan: packages: "你的项目组名.domain" properties: hibernate: hbm2ddl: auto: update show_sql: true format_sql: true
执行./gradlew run或测试时,Micronaut会自动启动PostgreSQL容器并完成连接,无需手动管理容器。
内容的提问来源于stack exchange,提问作者Bertuz
相关产品推荐
相关产品推荐

