上/下/随机" N"使用Hibernate Criteria / Projections
在每个组中的行如何检索每个子主题的前5个问题
DetachedCriteria criteria = DetachedCriteria.forClass(Question.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("questionId"));
projList.add(Projections.groupProperty("subTopicId"));
criteria.setProjection(projList);
List<Object> resultList = (List<Object>) getHibernateTemplate().findByCriteria(criteria);
Iterator<Object> itr = resultList.iterator();
List<Integer> questionIdList = new ArrayList<Integer>();
while(itr.hasNext()){
Object ob[] = (Object[])itr.next();
System.out.println(ob[0]+" -- "+ob[1]);
}
我正在使用下面的代码暂时获取结果,Hibernate是否有任何解决方案使用Criteria API /任何其他替代方法来获得结果
Set<Integer> getQuestionsBySubTopicWithLimit(Set<Integer> questionIdsSet, Integer subjectId, Integer limit, Integer status) {
DetachedCriteria criteria = DetachedCriteria.forClass(Question.class);
if(subjectId!=null && subjectId!=0){
criteria.add(Restrictions.eq("subjectId", subjectId));
}
if(status!=null){
criteria.add(Restrictions.eq("status", status));
}
if(questionIdsSet!=null && !questionIdsSet.isEmpty()){
criteria.add(Restrictions.not(Restrictions.in("questionId", questionIdsSet)));
}
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("questionId"));
projList.add(Projections.property("subTopicId"));
criteria.add(Restrictions.sqlRestriction("1=1 order by sub_topic_id, rand()"));
criteria.setProjection(projList);
List<Object> resultList = (List<Object>) getHibernateTemplate().findByCriteria(criteria);
Iterator<Object> itr = resultList.iterator();
Set<Integer> tmpQuestionIdsSet = new HashSet<Integer>();
Integer subTopicId = 0, tmpSubTopicId = 0;
Integer count = 0;
while(itr.hasNext()){
Object ob[] = (Object[])itr.next();
if(count==0){
subTopicId = (Integer) ob[1];
}
tmpSubTopicId = (Integer) ob[1];
if(tmpSubTopicId!=subTopicId){
subTopicId = tmpSubTopicId;
count = 0;
}
count++;
if(count<=limit){
tmpQuestionIdsSet.add((Integer) ob[0]);
}
}
return tmpQuestionIdsSet;
}