I needed to make the following SQL query with Hibernate
and being new to Hibernate it came out a lot differently than how I thought it would. To perform the IN query a Criteria query needs to be created
For the count and order by a Projection needs to be added to the criteria
This is the resulting code
Something completely different from what I expected. That's what I love about solving problems sometimes the solution is something you might never expect.
Download the source.
SELECT COUNT(*), state FROM download_request WHERE id IN (<id list>) GROUP BY state;
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids))
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
public Map getStateCounts(final Collection ids) {
HibernateSession hibernateSession = new HibernateSession();
Session session = hibernateSession.getSession();
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
Map stateMap = new HashMap();
for(Object[] obj: results) {
DownloadState downloadState = (DownloadState)obj[0];
stateMap.put(downloadState.getDescription().toLowerCase(), (Integer)obj[1]);
}
hibernateSession.closeSession();
return stateMap;
}







Be the first to comment.