1

This code is now deprecated, as of Hibernate 5.2:

    return (Long) sessionFactory.getCurrentSession().createCriteria(mainType)
            .setProjection(Projections.rowCount())
            .uniqueResult();

What is the proper/idiomatic way to remove the deprecation?

The note in the Hibernate API source code just says:

@deprecated (since 5.2) for Session, use the JPA Criteria

I realize there is something called a JPA Criteria Builder. This unfortunately is mis-named as it does not build JPA Criteria. It can however return a JPA Criteria Query:

CriteriaQuery<T> criteriaQuery = sessionFactory.getCriteriaBuilder().createQuery(mainType);

This, however, is a dead-end as the setProjection() method is missing.

Please note my question is specifically limited to Criteria Query on Hibernate 5.2+. There is a broader, older version of this question (How do we count rows using older versions of Hibernate (~2009)?)

Alex R
  • 11,364
  • 15
  • 100
  • 180
  • It's not a dead-end. The standard JPA Criteria API is more powerful than the old Hibernate criteria API, and is also more complex. Just because there is no `setProjection()` method doesn't mean that it's impossible to select a count. It's just done in a different way, that you need to learn. Using a criteria query for such a basic static query is really counter-productive, though. Why don't you use a JPQL query? – JB Nizet Nov 04 '18 at 19:01
  • @JBNizet my question has been distilled down from a larger example according to SO best-practice. This is known as an MCVE (Minimal, Complete, Verifiable Example) - https://stackoverflow.com/help/mcve - that is why it looks "counter-productive". – Alex R Nov 04 '18 at 19:44

0 Answers0