Hello, I have a JDBC query where each question mark represents a parameter which is later
set by Query.setLong(int paramIndex, Long value). The hibernate javadoc and it says that it
supports JDBC style '?' parameters. Is this true? I'm also having difficulties getting the count "count(c2.*)". Seems to be my syntax is wrong. Could somebody please help me out here. See below for code snippet.
Code:
@SuppressWarnings("unchecked")
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());
}