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

Hibernate聚合函数查询报‘holdings列不存在’错误求助

问题解决步骤

1. 修复SQL语法与字段问题

你遇到的column "holdings" does not exist错误,核心原因有两个:

  • SQL缺少FROM子句:查询未指定数据来源表,PostgreSQL无法识别字段所属的表。
  • 字段名不匹配:要么数据库表MstarHoldings中不存在holdings字段,要么你拼写错误(比如实际字段是holding或其他名称)。

修正后的SQL示例(请替换为实际字段名):

SELECT COALESCE(SUM(holdings), 0) AS total_holdings
FROM MstarHoldings
WHERE morningstar_investment_id = :investmentId 
  AND start_date BETWEEN :startDate AND :endDate
  • 用COALESCE确保无匹配记录时返回0,避免后续空指针问题。
  • 补充FROM MstarHoldings明确查询表。

2. 修正Hibernate代码问题

你的代码存在两处关键错误:

  • 实体类拼写错误:addEntity(MstarstarHoldings.class)中类名多了一个star,正确应为MstarHoldings;但更重要的是——聚合查询不需要绑定实体类,你要的是单一数值,而非完整实体对象。
  • 绑定实体类会导致映射错误:Hibernate会尝试将聚合结果映射到MstarHoldings实体,但查询仅返回一个数值,无法匹配实体的所有字段,必然触发异常。

修正后的代码:

// 方式1:直接强转(注意处理null场景)
Long sum = (Long) rdsSession.createNativeQuery(DBQueries.GET_FLOAT_SHARES)
        .setParameter("investmentId", investmentId, StringType.INSTANCE)
        .setParameter("startDate", filteredStartDate.get(i), LocalDateType.INSTANCE)
        .setParameter("endDate", filteredEndDate.get(i), LocalDateType.INSTANCE)
        .getSingleResult();

// 方式2:使用TypedQuery更安全
TypedQuery<Long> query = rdsSession.createNativeQuery(DBQueries.GET_FLOAT_SHARES, Long.class)
        .setParameter("investmentId", investmentId, StringType.INSTANCE)
        .setParameter("startDate", filteredStartDate.get(i), LocalDateType.INSTANCE)
        .setParameter("endDate", filteredEndDate.get(i), LocalDateType.INSTANCE);
Long sum = query.getSingleResult();

3. 额外注意事项

  • 若getSingleResult()可能返回null(无匹配记录),建议用getResultList()做安全处理:
    List<Long> resultList = query.getResultList();
    Long sum = resultList.isEmpty() ? 0L : resultList.get(0);
    
  • 确认数据库表的字段名、表名与代码完全一致(PostgreSQL默认区分大小写,若字段创建时加了引号需保持一致)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:15:43