You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hibernate转换@Column/@Table注解命名导致PostgreSQL查询失败

解决Hibernate将指定大驼峰表名/列名转为小写蛇形的问题

问题背景

实体类通过@Table(name = "Recipes")和@Column明确指定了大驼峰格式的表名与列名,且配置了ImplicitNamingStrategyJpaCompliantImpl,但Hibernate仍生成小写蛇形命名的SQL,导致PostgreSQL抛出relation "recipes" does not exist错误,实际执行的SQL如下:

select b1_0.id,b1_0.document_link,b1_0.user_email,b1_0.user_name from recipes b1_0 where b1_0.user_email=?

核心原因

  1. PostgreSQL标识符特性:PostgreSQL会将未被双引号包裹的标识符自动转换为小写,而实际的表/列是大驼峰命名,所以小写的recipes无法匹配大写开头的Recipes表。
  2. 命名策略配置不全:仅配置了隐式命名策略,但物理命名策略未指定,Hibernate默认的物理策略会将标识符转换为小写蛇形,覆盖了通过注解指定的名称。

解决方案

方案1:配置全局保留原始名称+强制加引号

修改application.properties,添加以下配置:

# 保留@Table/@Column指定的原始名称,不做转换
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
# 全局对所有标识符添加双引号,避免PostgreSQL自动转小写
spring.jpa.properties.hibernate.globally_quoted_identifiers=true

方案2:手动为注解中的名称添加引号

如果不想全局开启引号,可以在@Table和@Column的name属性中手动添加双引号(注意转义):

@Data
@Entity
@Table(name = "\"Recipes\"")
public class BoardRow {
    @Id
    @JsonProperty
    @Column(name = "\"Id\"")
    private String id;

    @JsonProperty
    @Column(name = "\"UserName\"")
    private String senderName;

    @JsonProperty
    @Column(name = "\"UserEmail\"")
    private String senderEmailAddress;

    @JsonProperty
    @Column(name = "\"DocumentLink\"")
    private String documentUrl;
}

验证

开启spring.jpa.show-sql=true,查看生成的SQL是否变为带双引号的大驼峰格式,例如:

select b1_0."Id",b1_0."DocumentLink",b1_0."UserEmail",b1_0."UserName" from "Recipes" b1_0 where b1_0."UserEmail"=?

内容的提问来源于stack exchange,提问作者illy sigelman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 18:12:50