Loc Phan
Loc Phan

Reputation: 4564

check exists in hibernate criteria API

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;
}

Upvotes: 8

Views: 6721

Answers (1)

JCalcines
JCalcines

Reputation: 1286

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.

Upvotes: 11

Related Questions