Rajesh Kumar
Rajesh Kumar

Reputation: 403

how to return a list of object which is not entity from a typed query in hibernate?

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

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.

Upvotes: 1

Views: 1167

Answers (1)

mentallurg
mentallurg

Reputation: 5207

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

Upvotes: 1

Related Questions