How to get Count in Hibernate 5 CriteriaBuilder with criteria condition

拟墨画扇 提交于 2019-12-11 01:13:42

问题


When I checked below code I got the count of all record. not condition wise.

CriteriaBuilder builder = getCurrentSession().getCriteriaBuilder();

    CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
    countQuery.select(builder.count(countQuery.from(ViewEmployees.class)));
    Long q1 = getCurrentSession().createQuery(countQuery).getSingleResult();

I want to get the count with criteria condition. like this code

CriteriaQuery<ViewEmployees> query = builder.createQuery(ViewEmployees.class);

        Root<ViewEmployees> root = query.from(ViewEmployees.class);

        List<Predicate> predicates = new ArrayList<Predicate>();

        // Equal Query
        if (StringUtils.isNotBlank(searchConditions.getCode())) {
            predicates.add(builder.and(builder.equal(root.get("code"), searchConditions.getCode())));
        }

Hibernate older version it was working with below code.

Criteria criteria = getApplicationEventConditions(searchCond);
        SearchTotals searchTotals = new SearchTotals();
        ProjectionList p1 = Projections.projectionList();
        p1.add(Projections.rowCount());
        criteria.setProjection(p1);
        List l = criteria.list();
        searchTotals.setTotalSize((Long) l.get(0));

Can you please anyone help me to solve this with CriteriaBuilder.

来源:https://stackoverflow.com/questions/52758885/how-to-get-count-in-hibernate-5-criteriabuilder-with-criteria-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!