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

Spring Boot+Hibernate+PostgreSQL报错:列role_id不存在(实际存在)

问题解决:PostgreSQL原生查询返回Role时报错“column name role_id was not found”

问题场景

在Spring Boot整合PostgreSQL与Hibernate的项目中,使用如下原生查询:

@Query(value = "SELECT json_data from xxxschema.roles  where role_id =?1", nativeQuery = true)
Role getRolePrivilegesByRoleId(int id);

执行时触发报错:

org.postgresql.util.PSQLException: 未在ResultSet中找到列名role_id。
at org.postgresql.jdbc.PgResultSet.findColumn(PgResultSet.java:2748) ~[postgresql-42.2.16.jar:42.2.16]

原因分析

你的查询只返回了json_data一列,但方法声明返回Role实体类。Hibernate在把查询结果映射到Role对象时,需要填充实体类中所有被映射的字段(包括role_id),但当前ResultSet里没有这个字段,所以抛出找不到列的异常。

解决方案

根据实际需求选择对应方案:

  • 仅需json_data字段:修改返回类型
    如果业务上只需要json_data的内容,直接把方法返回类型改成对应的数据类型(比如String):

    @Query(value = "SELECT json_data from xxxschema.roles  where role_id =?1", nativeQuery = true)
    String getRolePrivilegesByRoleId(int id);
    
  • 需要完整Role对象:查询必要字段
    要么明确查询Role实体类映射的所有字段,要么至少包含role_id和json_data:

    @Query(value = "SELECT role_id, json_data from xxxschema.roles  where role_id =?1", nativeQuery = true)
    Role getRolePrivilegesByRoleId(int id);
    

    也可以用SELECT *(不推荐生产环境使用,避免后续表字段变更引发映射问题):

    @Query(value = "SELECT * from xxxschema.roles  where role_id =?1", nativeQuery = true)
    Role getRolePrivilegesByRoleId(int id);
    
  • 仅需部分字段但要返回Role对象:自定义结果集映射
    在Role实体类上定义@SqlResultSetMapping,指定要映射的字段:

    @Entity
    @SqlResultSetMapping(
        name = "RoleJsonMapping",
        classes = @ConstructorResult(
            targetClass = Role.class,
            columns = {
                @ColumnResult(name = "role_id", type = Integer.class),
                @ColumnResult(name = "json_data", type = String.class)
            }
        )
    )
    public class Role {
        // 实体类字段及JPA映射注解
    }
    

    然后在查询注解中指定这个映射:

    @Query(value = "SELECT role_id, json_data from xxxschema.roles  where role_id =?1", nativeQuery = true, resultSetMapping = "RoleJsonMapping")
    Role getRolePrivilegesByRoleId(int id);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:40:29