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

如何使用Quarkus PanacheEntity查询非主键列的去重值?

问题描述

我有一张MySQL表,结构及数据如下:

(ID(primary-key), Name, rootId)
(2, asdf, 1)
(3, sdf, 1)
(12, tew, 4)
(13, erwq, 4)

我希望查询数据库中去重的rootId值,预期结果为1、4。

我尝试了以下代码:

List<Entity> entityList = Entity.find("SELECT DISTINCT t.rootId from table t").list();

调试时发现查询结果确实是"1"、"4",但Entity.find()只能返回Entity对象,查询结果是数值类型,无法完成类型转换。

请问是否有方法通过PanacheEntity获取非主键列的去重值?

解决方案

可以通过以下几种方式实现:

  • 投影查询返回特定字段类型:Panache支持直接返回单个字段的列表,无需封装成完整Entity对象。根据rootId的实际数据类型调整返回类:

    // 若rootId是Long类型
    List<Long> rootIds = Entity.find("SELECT DISTINCT t.rootId FROM table t").project(Long.class).list();
    // 若rootId是Integer类型
    List<Integer> rootIds = Entity.find("SELECT DISTINCT t.rootId FROM table t").project(Integer.class).list();
    
  • Panache链式查询风格:利用select和distinct方法简化写法:

    List<Long> rootIds = Entity.findAll().select("rootId").distinct().project(Long.class).list();
    
  • 原生SQL查询:如果更习惯原生SQL语法,也可以这样写:

    List<Long> rootIds = Entity.find("SELECT DISTINCT rootId FROM table").project(Long.class).list();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:30:46