8

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;
}
2
  • edited: add base code of count by criteria Commented Nov 5, 2013 at 8:26
  • There is no question. Also, as far as I know, it is fairly common to use count as exists criteria. Commented Nov 5, 2013 at 9:01

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.