Spring Boot连接Heroku PostgreSQL数据库失败问题求助
解决Spring Boot连接Heroku PostgreSQL的UnknownHostException问题
看起来你遇到的核心问题是数据库连接URL格式错误,导致HikariCP无法正确解析数据库主机地址,同时配置文件里还有几处拼写错误需要修正。让我们一步步拆解解决:
1. 修正JDBC连接URL格式
你的spring.datasource.url里存在明显的格式错误:jdbc:postgresql://@host:5432/...,这里的@符号位置完全不对。PostgreSQL JDBC URL的标准格式是:
jdbc:postgresql://[username:password@]host:port/database?params
你现在的写法把@直接放在主机名前面,没有对应的用户名密码前缀,导致JDBC驱动错误地把@host当成了完整的主机名,这就是UnknownHostException的直接诱因。
两种靠谱的修正方案:
- 方案一:保留单独的
spring.datasource.username和spring.datasource.password配置,URL只保留主机、端口和数据库信息:spring.datasource.url=jdbc:postgresql://YOUR_HOST:5432/dal2fiqv9or5eg?sslmode=require - 方案二:把用户名密码整合到URL中(注意要删除单独的username/password配置,避免双重配置冲突):
spring.datasource.url=jdbc:postgresql://YOUR_USERNAME:YOUR_PASSWORD@YOUR_HOST:5432/dal2fiqv9or5eg?sslmode=require
2. 修正application.properties的拼写错误
你的配置里有两处关键拼写错误,会直接影响JPA的正常工作:
spring.jpa-hibernate.ddl-auto→ 应该是spring.jpa.hibernate.ddl-auto(用.代替-,这是Spring Boot统一的配置命名规范)spring.jpa.show=true→ 应该是spring.jpa.show-sql=true(正确的配置项是show-sql,用来开启SQL执行日志)
修正后的完整配置示例(方案一):
spring.datasource.url=jdbc:postgresql://YOUR_HOST:5432/dal2fiqv9or5eg?sslmode=require spring.datasource.username=YOUR_USERNAME spring.datasource.password=YOUR_PASSWORD spring.datasource.driver-class-name=org.postgresql.Driver spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect spring.jpa.properties.hibernate.format_sql=true
3. 调整H2数据库依赖
你的POM里引入了H2数据库但没有指定scope,这可能会在运行时和PostgreSQL驱动产生不必要的冲突。如果H2只是用于测试场景,建议给它加上test scope:
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency>
验证思路
你提到Express应用能成功连接,说明数据库的主机、用户名、密码都是正确的,所以问题完全出在Spring Boot的配置格式上。按照上面的步骤修正后,HikariCP应该能正常初始化连接池,解决启动时的异常问题。
内容的提问来源于stack exchange,提问作者Kalio O'Farril
相关产品推荐
相关产品推荐

