如何在新的 dto 查询中按计算列排序

How to order by computed column in new dto query

我有这个查询:

em.createQuery("select new SomeDto(some.name, " +
"(select max(other.weight) from Other other where other.someId = some.id) as otherWeight" +
") from Some some order by otherWeight")
.getResultList();

这不起作用,因为休眠会忽略 as otherWeight,而只是生成 as col_1_0_

有没有办法通过这种 select new dto 查询来获取列的别名? 如果不是:我如何进行这样的查询(将查询结果映射到 DTO 构造函数)?

您可以试试下面的查询,应该也会更快:

select new SomeDto(some.name, max(other.weight))
from Other other right outer join other.some some
group by some.id, some.name
order by max(other.weight)

如果您还没有多对一(或一对一)关联,则需要引入从 OtherSome 的关联。