首页 > 解决方案 > 如何从休眠中的类型化查询返回不是实体的对象列表?

问题描述

我需要从实体类 Employee 中提取一些字段并添加一些额外的硬编码字段并使用 GROUP BY 子句返回结果。

下面是我试过的代码:

String query = "SELECT emp.category, emp.salary  0 as somevalue, 0 as dummy FROM employee emp "
                + "WHERE emp.date = :date AND emp.class = :class AND emp.classificationDetail.shortDescription = :classificationType GROUP BY emp.category";

        TypedQuery<CustomEmployee> typQuery = entityManager.createQuery(query, CustomEmployee.class);

        typQuery.setParameter("date", req.getDate());
        typQuery.setParameter("class", req.getClass());


        return typQuery.getResultList();

但是我遇到了异常,即无法使用请求的结果类型为具有多个返回的查询创建 TypedQuery。

如何实现这一点。谢谢。

标签: javadatabasehibernate

解决方案


首先检查这部分:emp.salary 0 as somevalue。这应该是emp.salary as somevalue0 as somevalue,但不能两者兼而有之。

定义一个如下所示的类(保持简短;我使用公共属性,但您可以根据需要更改它):

public class CustomEmployee {
    public String category;
    public Double salary;
    public Double dummy;
    ...
}

在查询中使用它如下:

String query = "SELECT new mypackage.CategorySalary( " +
    "    emp.category, " +
    "    emp.salary as somevalue, " +
    "    0 as dummy " +
    ") from ...  " +
    "WHERE ...  ";

TypedQuery<CustomEmployee> typQuery = entityManager.createQuery(query, CustomEmployee.class);

推荐阅读