How to best express "exists" query with Hibernate Criteria?
In my project, people use count projections to check if any row matches the criteria (count > 0). To be more effective, I prefer using exists instead.
Here is the base code for counting by criteria:
public int count(final DetachedCriteria criteria) throws DataAccessException {
Object countResult = executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria executableCriteria = criteria.getExecutableCriteria(session);
executableCriteria.setProjection(Projections.rowCount());
prepareCriteria(executableCriteria);
return executableCriteria.uniqueResult();
}
});
if (countResult == null) {
countResult = 0;
}
return (Integer) countResult;
}