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

Spring Boot+Hibernate操作PostgreSQL列名大小写匹配异常解决

Spring Boot + PostgreSQL:Hibernate生成全小写列名导致查询失败的解决方案

问题场景

我有一个基于Spring Boot的应用,连接PostgreSQL数据库时遇到Hibernate生成SQL列名大小写不匹配的问题:

  1. Photographer实体类片段:
@Entity
@Table(name = "photographer", schema = "public")
@Data
@NoArgsConstructor
public class Photographer {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    private String additionalInfo;
    private String location;
    private String portfolio;
    // 其他属性...
}
  1. Liquibase建表语句:
<createTable tableName="photographer">
    <column name="id" type="bigint">
        <constraints primaryKey="true" primaryKeyName="photographer_id_pk" />
    </column>
    <column name="name" type="varchar(100)"/>
    <column name="additionalInfo" type="varchar(100)"/>
    <column name="location" type="varchar(100)"/>
    <column name="portfolio" type="varchar(100)"/>
    <column name="linksToSocials" type="varchar(100)"/>
    <column name="offer" type="varchar(255)"/>
    <column name="reviews" type="varchar(100)"/>
    <column name="commuting" type="varchar(100)"/>
    <column name="devices" type="varchar(100)"/>
</createTable>
  1. JpaRepository接口:
@Repository
public interface PhotographerRepository extends JpaRepository<Photographer, Long> {
}

调用findAll()时抛出错误:

org.postgresql.util.PSQLException: ERROR: column p1_0.additionalinfo does not exist

排查发现:数据库中实际列名为驼峰格式的additionalInfo,但Hibernate生成的SQL使用了全小写的additionalinfo,导致匹配失败。尝试过调整Hibernate方言和命名策略:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

但问题未解决,且常规的蛇形转驼峰方案不适用(当前场景是Hibernate直接将驼峰列名转为全小写)。

有效解决方案

添加以下配置,强制Hibernate对所有标识符(表名、列名)添加引号,保留原大小写格式:

spring.jpa.properties.hibernate.globally_quoted_identifiers=true

原理说明

PostgreSQL默认行为是:未加引号的标识符会被自动转换为小写。而Hibernate默认生成的SQL中,列名不会添加引号,因此additionalInfo会被PostgreSQL识别为additionalinfo,与数据库中实际存在的驼峰列名不匹配。

开启globally_quoted_identifiers=true后,Hibernate会给所有生成的SQL中的标识符加上双引号,此时PostgreSQL会严格按照引号内的大小写来匹配列名,从而解决大小写不匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 08:17:34