0

假设,我需要根据某些条件使用 Hibernate 计算数据库表中的行数,我可以org.hibernate.criteria像下面这样使用。

@Service
@Transactional(readOnly = true, propagation=Propagation.REQUIRES_NEW)
public final class StateDAO implements StateService
{
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Object rowCount(String id)
    {
        return sessionFactory.getCurrentSession()
              .createCriteria(State.class)
              .setProjection(Projections.rowCount())
              .add(Restrictions.eq("countryId", Long.parseLong(id)))
              .uniqueResult();
    }
}

它根据id通过 Spring 提供的行数来计算行数。

这也可以通过使用类似的 HQL 查询来实现。

sessionFactory.getCurrentSession()
              .createQuery("select count(*) as cnt from State where countryId=:id")
              .setParameter("id", Long.valueOf(id).longValue())
              .uniqueResult();

哪个更好且更常见(关于性能和其他方面)?

4

1 回答 1

2

在您的情况下,这是一个偏好问题。Criteria API 是类型安全的,并且可能更快(您无需为解析 HQL 付出代价)。另一方面,HQL 可能更容易阅读,尤其是对于具有 SQL 背景的人。

您应该使用条件 API的唯一地方是查询是动态的,例如,基于某些输入,可以选择 WHERE 条件的任何子集。使用 HQL,您将不得不从字符串构建 HQL(看起来很糟糕),或者有指数级数量的略有不同的 per-coined 查询。

于 2013-01-31T21:07:05.457 回答