Issue with selecting max id rows using criteria query / hibernate query?

断了今生、忘了曾经 提交于 2019-12-07 16:47:19

问题


I am unable to select the rows where TestId is max for respective student, I wrote the code as follows which does not get the required output. my code is as follows,

Criteria c = sessionFactory.getCurrentSession().createCriteria(student.class).setProjection(Projections.projectionList().add(Projections.property("answer"),"answer"));
c.add(Restrictions.eq("surveyId",send_Survey));
//c.add(Restrictions.eq("testId", "1" ));
//c.setProjection(Projection.max("testId"));
c.addOrder(Order.desc("testId"));
c.add(Restrictions.eq("questionid",FinalQuestionsOne));
List<String> age=c.list();

My table structure is as follows,

I need the following output. select the answer column for max TestId's. How can I get the output using criteria query


回答1:


So I think what you're trying to get can be achievedd by the following sql:

SELECT TestId, MAX(answer) WHERE questionId = 1 GROUP BY TestId;

You should be able to achieve this with the following Hibernate:

sessionFactory.getCurrentSession().createCriteria(student.class).setProjection(Projections.projectionList()
                        .add(Projections.property("TestId"), "TestId")
                        .add(Projections.groupProperty("TestId"))
                        .add(Projections.max("answer")));


来源:https://stackoverflow.com/questions/23489359/issue-with-selecting-max-id-rows-using-criteria-query-hibernate-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!