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;
}
Sometime ago, I had the same doubt and I thought that It is unefficient. So what I do now I search the first coincidence and that is faster.
protected boolean exists(final Criteria query) {
query.setProjection(Projections.id());
query.setMaxResults(1);
return query.uniqueResult() != null;
}
I hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With