如何使用Hibernate Criteria创建查询

时间:2015-03-09 10:05:07

标签: java hibernate

我必须使用Criteria创建以下查询:

SELECT r.*,( 
         SELECT COUNT(*) FROM APP.P_FORM_QUESTION_ANSWER qa 
         WHERE qa.J_STATUS = 'CORRECT' 
         AND qa.J_FORM_ID = r.J_FORM_ID AND qa.J_AUTHOR_ID = r.J_AUTHOR_ID 
         AND qa.J_FORM_RESULT_ID = r.J_ROW_ID
       ) as correctCount
FROM APP.P_FORM_RESULT r
WHERE r.J_FORM_ID = '123456'
ORDER BY correctCount DESC;

我尝试将DetachedCriteria用于额外的列,但我不知道如何表示:

"qa.J_FORM_ID = r.J_FORM_ID AND qa.J_AUTHOR_ID = r.J_AUTHOR_ID 
 AND  qa.J_FORM_RESULT_ID = r.J_ROW_ID" 
在DetachedCriteria中

,并将我的DetachedCriteria添加为新列

Criteria criteria =  
    HibernateUtil.getSession().createCriteria(FormResult.class, "formResult");
criteria.add(Restrictions.eq("formResult.formId", formId));

DetachedCriteria correctCount =  
    DetachedCriteria.forClass(QuestionAnswer.class, "questionAnswer");

correctCount.add(
      Restrictions.eq("questionAnswer.status",QuestionAnswerStatus.CORRECT));

// How to retrieve 'formResult' ?
correctCount.add(Restrictions.eq("questionAnswer.formId", "formResult.formId")); 

// How to retrieve 'formResult' ?
correctCount.add(Restrictions.eq("questionAnswer.authorId", "formResult.authorId"));  


 // How to retrieve 'formResult' ?
correctCount.add(
    Restrictions.eq("questionAnswer.formResult.rowId", "formResult.rowId"));
correctCount.setProjection(Projections.rowCount());

// How to add my DetachedCriteria as a new column
criteria.setProjection(Projections.alias(correctCount, "correctCount"));

带注释的行是我找不到解决方案的行。

1 个答案:

答案 0 :(得分:0)

最后,我创建了一个不同的SQL查询,它给出了相同的结果:

SELECT r.J_ROW_ID, COUNT(DISTINCT qa.J_ROW_ID) as correctCount
FROM APP.P_FORM_RESULT r left join APP.P_FORM_QUESTION_ANSWER qa on qa.J_FORM_ID = r.J_FORM_ID AND qa.J_AUTHOR_ID = r.J_AUTHOR_ID AND qa.J_FORM_RESULT_ID = r.J_ROW_ID AND qa.J_STATUS = 'CORRECT'
WHERE r.J_FORM_ID = '123456'
GROUP BY r.J_ROW_ID
ORDER BY correctCount DESC;

我使用HQL是因为我无法在Criteria中找到如何做到这一点:

// HQL Query to retrieve the list of FormResult IDs
StringBuilder hql = new StringBuilder();
hql.append("SELECT r.id");
hql.append(" FROM QuestionAnswer qa RIGHT JOIN qa.formResult as r");
hql.append(" WHERE r.formId = :formId AND (qa.status = :status OR qa.status IS NULL)");
hql.append(" GROUP BY r.id");
hql.append(" ORDER BY COUNT(DISTINCT qa.id) DESC"));

Query query = HibernateUtil.getSession().createQuery(hql.toString());
query.setParameter("formId", formId);
query.setParameter("status", QuestionAnswerStatus.CORRECT);

// Retrieve the list of FormResult objects from the list of IDs previously retrieved
List<Long> result = query.list();
if (result != null && !result.isEmpty()) {
  for (Long resultId : result) {
    formResults.add(getData(FormResult.class, resultId));
  }
}

缺点是我必须从我的HQL查询检索到的ID列表中逐个检索每个FormResult