8

如何用 Hibernate Criteria 最好地表达“存在”查询?

在我的项目中,人们使用计数预测来检查是否有任何行符合条件(计数 > 0)。为了更有效,我更喜欢使用 exists 代替。

以下是按标准计数的基本代码:

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

1 回答 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.

于 2013-11-05T09:59:05.493 回答