Rox
Rox

Reputation: 2917

How do I get the highest value from a table using Hibernate Query Language?

I am trying to get the highest value from a table, but the value must have been set within the last 5 days.

The query below seems to work but how do I write it in Hibernate Query Laguage, HQL?

  SELECT MAX(my_value) as my_value FROM Character WHERE create_date > now() + interval '-5 day'

I have tried to make the above sql statement as a native query but then it complains about that some fields coudln´t be found (I guess that Hibernate tries to set all the fields in the entity but the above sql just returns one column/row called 'my_value').

Upvotes: 0

Views: 1094

Answers (1)

Karibasappa G C
Karibasappa G C

Reputation: 2732

you can do it like below

first get the date for last 5th day using java

Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, -6);
Date d = c.getTime();

select c.my_value from Character c 
where  c.my_value = 
     (select max(cc.my_value) from Character cc where cc.create_date > d )

make sure Character class has the attributes my_value and create_date correctly, and use them as it is in Character entity class not as it is in table.

Upvotes: 1

Related Questions