I have this code
final Session session = sessionFactory.getCurrentSession();
final CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
final CriteriaQuery<ListingDetailBaseDto> criteria = builder.createQuery(ListingDetailBaseDto.class);
final Root<ListingDetailBaseDto> root = criteria.from(ListingDetailBaseDto.class);
...
public int countRecords() {
final CriteriaQuery<Long> countingQuery = builder.createQuery(Long.class);
countingQuery.select(countingQuery.from(Long.class));
countingQuery.select(builder.count(root));
final Query<Long> query = session.createQuery(countingQuery);
return query.getSingleResult().intValue();
}
It says Long is not a valid entity. So I remove line 3,
public int countRecords() {
final CriteriaQuery<Long> countingQuery = builder.createQuery(Long.class);
countingQuery.select(builder.count(root));
final Query<Long> query = session.createQuery(countingQuery);
return query.getSingleResult().intValue();
}
And then the error becomes: No criteria query roots were specified
How can I get this simple record count???
Thanks @O.Badr for asking about root
, that got me looking a little more closely at that part of the code.
The problem was caused by using root
from a different CriteriaQuery
object.
Fixed code:
public int countRecords() {
final CriteriaQuery<Long> countingQuery = builder.createQuery(Long.class);
countingQuery.select(builder.count(countingQuery.from(ListingDetailBaseDto.class)));
final Query<Long> query = session.createQuery(countingQuery);
return query.getSingleResult().intValue();
}