0
我想獲得以下查詢功能,但我遇到了查詢的createSQL部分以及StringBuilder部分的困難。任何幫助將不勝感激。休眠查詢createSQLQuery
protected List<CategoryNode> findByCriterion(Criterion criterion) {
List<Category> cats = session.createCriteria(Category.class).add(criterion).list();
Map<Integer, CategoryNode> childNodes = new LinkedHashMap<Integer, CategoryNode>();
for (Category cat : cats) {
CategoryNode childNode = new CategoryNode();
childNode.setCategory(cat);
childNodes.put(cat.getId(), childNode);
}
StringBuilder questions = new StringBuilder();
for (int i = 0; i < childNodes.size(); ++i) {
if (i != 0) {
questions.append(", ");
}
questions.append("?");
}
Query query = session.createSQLQuery(
"select c1.id, count(c2.*) "
+ "from Category c1 "
+ "left join Category c2 on c2.parentCategoryId = c1.id "
+ "where c1.id in (" + questions + ") "
+ "group by c1.id");
int i = 0;
for (Iterator<CategoryNode> it =
childNodes.values().iterator(); i < childNodes.size(); ++i) {
query.setLong(i + 1,
it.next().getCategory().getId());
}
for (Iterator<Object[]> it = query.iterate(); it.hasNext();) {
Object[] result = it.next();
Integer childId = (Integer) result[0];
Integer grandChildCount = (Integer) result[1];
CategoryNode childNode = childNodes.get(childId);
childNode.setHasChildren(grandChildCount != 0);
childNode.setIsLeaf(grandChildCount == 0);
}
return new ArrayList<CategoryNode>(childNodes.values());
}
您可以發佈您的輸出嗎? – subodh 2012-02-16 14:24:13
可以在日誌中發佈錯誤消息嗎? – ManuPK 2012-02-16 15:12:34
我沒有在我面前的應用程序,但我得到一個與count(c2。*)相關的異常,說它不喜歡。 createSQLQuery是否包含正確的語法? – 2012-02-16 20:13:02