Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check exists in hibernate criteria API

Tags:

hibernate

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;
}
like image 597
Loc Phan Avatar asked Nov 05 '13 08:11

Loc Phan


1 Answers

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.

like image 158
JCalcines Avatar answered Sep 24 '22 01:09

JCalcines