I have a table "questions" which has fields id, version along with other fields. A question can have multiple records with the same id and different version. I need to select the question record for each question with the highest version.
My sql query is
select * from questions v1 inner join
(select id, max(version) as highest_version from
questions group by id
)as v2 on v1.id = v2.id and v1.version = v2.highest_version;
This query works from Sequel pro. But I need to run this from Java and I am using hibernate.
My Java code is:
String assertQuestionQuery = "select v1 from Question v1 inner join "
+ "(select t.id, max(t.version) as highest_version "
+ "from Question t "
+ "group by t.id) "
+ "as v2 on v1.id = v2.id and v1.version = v2.highest_version";
Query q = sourceEm.createQuery(assertQuestionQuery, Question.class);
List<Question> questionVersions = q.getResultList();
I am getting the following error:
ERROR org.hibernate.hql.internal.ast.ErrorCounter line 1:87: unexpected token: (
If I remove the parenthesis I am getting the following error:
ERROR org.hibernate.hql.internal.ast.ErrorCounter line 1:87: unexpected token: select
createNativeQueryinstead ofcreateQueryand update the query, useselect v1.* frominstead ofselect v1 from