泛型参数通常是为 a 指定的TypedQuery
。如果您声明 aTypedQuery
您将使用 anObject[]
作为 的通用参数TypedQuery
,因为您正在投影列而不是返回完整的实体。
但是,由于您尚未声明 a TypedQuery
(您使用简洁的编码风格),因此您需要更改Debit.class
为,Object[].class
因为您没有选择对象,而是只选择两个字段。
Object[] result = entityManager.createQuery("select dd, MAX(dd.createdMillis) from T_DEBIT dd" +
" where dd.debitStatus in (:debitStatus)" +
" and dd.account = :account" , Object[].class) //Notice change
.setParameter("debitStatus", false)
.setParameter("account", account)
.getSingleResult();
执行此查询将返回一个Object[]
where 中的每个索引Object[]
与您的 select 语句中的一个字段相对应。例如:
result[0] = dd
result[1] = max(dd.createdMillis)
为避免使用 ,Object[]
您可以创建一个新类以更强类型的方式检索这些值。就像是:
public class Result {
String dd;
Date createdMillis;
public Result(String dd, Date createdMillis) {
super();
this.dd = dd;
this.createdMillis = createdMillis;
}
public String getDd() {
return dd;
}
public void setDd(String dd) {
this.dd = dd;
}
public Date getCreatedMillis() {
return createdMillis;
}
public void setCreatedMillis(Date createdMillis) {
this.createdMillis = createdMillis;
}
}
然后在您的 JPQL 语句中,您可以调用构造函数:
Result result = entityManager.createQuery("select NEW fully.qualified.Result(dd, MAX(dd.createdMillis)) from T_DEBIT dd" +
" where dd.debitStatus in (:debitStatus)" +
" and dd.account = :account" , Result.class)
.setParameter("debitStatus", false)
.setParameter("account", account)
.getSingleResult();
最近,我写了一篇关于这个确切主题的博客。我鼓励您观看我创建的这个视频教程:https ://tothought.cloudfoundry.com/post/16