如何从休眠中的类型化查询返回不是实体的对象列表? [英] how to return a list of object which is not entity from a typed query in hibernate?

查看:69
本文介绍了如何从休眠中的类型化查询返回不是实体的对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to pull few fields from entity class Employee and add few extra hard coded field and return the result using GROUP BY clause.

下面是我尝试过的代码:

Below is the code I tried:

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。

But I am getting exception that Cannot create TypedQuery for query with more than one return using requested result type.

如何实现这一目标。
谢谢。

How to achieve this. Thanks.

推荐答案

首先检查此部分: emp.salary 0作为somevalue 。这应该是 emp.salary作为某值 0作为某值,但不能两者都使用。

First check this part: emp.salary 0 as somevalue. This should be either emp.salary as somevalue or 0 as somevalue, but not both.

定义如下所示的类(为了简短起见;我使用公共属性,但可以根据需要更改它):

Define a class like following (to keep it short; I use public properties, but you can change it if you want):

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

在查询中使用它的方式如下:

The use it in the query as follows:

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);

这篇关于如何从休眠中的类型化查询返回不是实体的对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆