pmestima
pmestima

Reputation: 119

JPA Hibernate cast to non Entity class

I have a big database and I need to make a query that join with, at least, 3 tables. The problem is that the resultset from this query isn't an Entity class.

The query:

SELECT avg(g.grade) avgGrade, max(g.grade) maxGrade, min(g.grade) minGrade FROM...

The new class:

class Stat {
  float avgGrade;
  float maxGrade;
  float minGrade;

  // constructor + getters and setters
}

Now I need to get that three values from the query. How can I do that?

Upvotes: 1

Views: 891

Answers (4)

pmestima
pmestima

Reputation: 119

I found the problem, the avg(g.grade) returns a double and my class Stat's constructor accept a float, so I have an error related to not found constructor exception.

Thanks to all :)

Upvotes: 0

Adrian Shum
Adrian Shum

Reputation: 40066

You have two choices (I think there is more but these two should be the most common one), first using the way Nayan Wadekar suggest, which construct the data object by constructor.

The second one is just select the fields you want, and Hibernate is going to return you a list of tuples. Each element of the list is an Object[], which represents one "row" of result. You can self-implement the transformation from tuple to your Stat class.

Upvotes: 0

Harinder
Harinder

Reputation: 11944

Assuming that the class Stat has an appropriate constructor

select new your_pkg_name.Stat(avg(g.grade) as avgGrade, max(g.grade)  as maxGrade, min(g.grade) as minGrade) FROM ...

Upvotes: 0

Nayan Wadekar
Nayan Wadekar

Reputation: 11622

You can try the below query using Constructor Expression, modify it accordingly.

SELECT NEW package_name.Stat(avg(g.grade), max(g.grade), min(g.grade)) FROM ...

Upvotes: 1

Related Questions