简体   繁体   中英

How to count of number of rows in Criteria Api

What I'm trying to do is count rows fit to typed criteria (I need to warn user that lookup will spend some time x rows * (estimated time for one row) , my code looks like :

CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Long> criteria = qb.createQuery(Long.class);
Root<TrackingDAO> p = criteria.from(TrackingDAO.class);
criteria.select(qb.count(criteria
            .from(TrackingDAO.class)));
/* my stuff with criteria */ 
TypedQuery<Long> q = em.createQuery(criteria);
setCounterOfLookUpResults(q.getSingleResult());

Class is working fine , until I got results, they are totally weird like eg 56432 and I'm expecting eg 430 .

Can somebody tell me how to "ping" database and ask how many rows it's going to provide me before I'm fetching that rows ?

Use Projections to get row count from criteria

  criteria.setProjection(Projections.rowCount());
  return Integer.parseInt(criteria.list().get(0).toString());

or

criteria.select(qb.count(p.get(TrackingDAO_.id)));

所有看起来像我的情况下的count方法在执行我的代码时返回每一个动作,我假设数字如:6949360当查询返回430结果时,“仅”1131当我有1个结果

Most databases don't know what you're going to ask for before you ask for it depending on your WHERE clause. So the most generic way of doing this would be to write a method that takes your table, and your where clause and does a count(*) against it and tells you how many rows would match your query.

You can use Projections to get the row count

criteria.setProjection(Projections.rowCount());
int count = Integer.valueOf(criteria.uniqueResult());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM