I’m trying to get the following query to function but I’m having difficulties with the createSQL portion of the query as well as the StringBuilder section. Any help will be appreciated.
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());
}
resolved needed to replace c2.* with c2.id.