当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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

网友答案:

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")));
分享给朋友:
您可能感兴趣的文章:
随机阅读: