【问题标题】:order by when using Constructor Expressions in JPA 2在 JPA 2 中使用构造函数表达式时排序
【发布时间】:2015-05-07 11:14:49
【问题描述】:

作为 JSR-338 的一部分,出现了使用构造函数表达式的特性。 问题是在使用构造函数表达式时如何使用order by

以 JPQL 为例:

select com.acme.AggregatedInfo(
    c,
    (select status from Account where ssn = c.ssn)
)
from Customer c 
where m.id in (:customerIdList)    

还有 AggregatedInfo 类

class AggregatedInfo {

    private final Customer customer;
    private final String status;

    public AggregatedInfo(Customer customer, String status) {...}

    // boilerplate javacode....
}

我在这样的 DAO 中使用它:

public List<AggregatedInfo> getAggregatedResult(final List<Long> customerIdList)
    return em.createQuery(hql, AggregatedInfo.class)
        .setParameters("customerIdList", customerIdList)
        .getResultList();
}

如果我想按状态订购 - 如何通过 JPQL 完成?

我尝试了以下方法但没有成功:

select com.acme.AggregatedInfo(
    c,
    (select status from Account where ssn = c.ssn)
) as a
from Customers c 
where m.id in (:customerIdList)    
order by c.status

但这不起作用。

可行吗? 请解释一下。

【问题讨论】:

  • 您使用的是 JPA 特定的方法和类还是 Hibernate?
  • 我正在使用 JPA api
  • 你能告诉我你的 DAO 课程吗?
  • 我已将 dao 代码添加到问题中。

标签: java hibernate jpql jpa-2.1


【解决方案1】:

试试下面的。它在 Hibernate 中使用类似的实现对我有用。它也应该适合你

public List<AggregatedInfo> getAggregatedResult(final List<Long> customerIdList)
    return em.createNativeQuery(hql, AggregatedInfo.class)
        .setParameters("customerIdList", customerIdList)
        .getResultList();
}

entityManager.createQuery() 替换为entityManager.createNativeQuery()

【讨论】:

  • 使用原生查询时可以使用order by吗?
  • 是的,你可以试试看。 Hibernate 是 JPA 的出色实现,它提供了出色的功能。它在那里对我有用,它应该对你有用
  • @stalet NativeQuery 术语不言自明。你可以传递纯 SQL 查询作为参数来创建 JPA 的 Query 对象并获取 List I
  • 似乎我得到一个 MappingException 告诉我 AggregatedInfo 不是一个实体。当使用本机查询时,我还必须添加一些映射配置......我会尝试重写很多!
  • 没问题,尝试将em.createNativeQuery(hql, AggregatedInfo.class) 替换为em.createNativeQuery(hql)。输出将与您想要的相同。如果一开始这对您不起作用,请尝试在您的 class AggregatedInfo 顶部添加 @Entity 注释。虽然我不知道 JPA 是否支持注释。尝试添加,然后按 CTRL+ SHIFT+ I tocken 让您的 IDE 为它找到合适的包
猜你喜欢
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 2020-04-27
  • 1970-01-01
  • 2021-01-09
相关资源
最近更新 更多