[英]JPA count(*) using CriteriaBuilder
I have a question about CriteriaBuilder API.我有一个关于 CriteriaBuilder API 的问题。 I am new in JPA, I would like to create a count(*) thought a CriteriaBuilder.
我是 JPA 的新手,我想创建一个计数(*) ,并认为是 CriteriaBuilder。 The count that I need to create needs to use the same parameters that I using in this dynamic query, that I created
我需要创建的计数需要使用我在此动态查询中使用的相同参数,我创建
I have this service to create a dynamic query but I do not have an idea to how to create a count(*) using the same parameters我有这项服务来创建动态查询,但我不知道如何使用相同的参数创建计数(*)
package com.sanmina.rohsappapirest.model.services.imp;
/**
* @author edgar_conrado on 07/07/2020
*
*/
@Service
public class ItemFilterServiceImp implements IItemFilterService {
@Autowired
private IItemFilterDao itemFilterDao;
/**
* This function to get the items providing parameters
*
* @param manufacturers Array with the manufacturer to found
* @param mpnReachs Array with the mpnReachs to found
*
* @return List with the items
*/
@Override
@Transactional(readOnly = true)
public List<ItemFilter> findByInManufacturer(String[] manufacturers, String[] mpnReachs) {
return itemFilterDao.findAll(new Specification<ItemFilter>() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public Predicate toPredicate(Root<ItemFilter> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
// Criteria for Manufacturer
if (manufacturers!=null) {
// Convert the array in a List
List<String> manufacturerList = new ArrayList<String>();
for (String l : manufacturers) {
manufacturerList.add(l);
}
//Create the query
In<String> predicate = criteriaBuilder.in(root.get("manufacturer"));
manufacturerList.forEach(t -> predicate.value(t));
predicates.add(predicate);
//predicates.add(criteriaBuilder.and(criteriaBuilder.in(root.get("manufacturer"))));
}
// Criteria for Reach
if (mpnReachs!=null) {
// Convert the array in a List
List<String> reachList = new ArrayList<String>();
for (String l : mpnReachs) {
reachList.add(l);
}
//Create the query
In<String> predicate = criteriaBuilder.in(root.get("mpnReach"));
reachList.forEach(t -> predicate.value(t));
predicates.add(predicate);
}
return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
});
}
}
Any suggestion?有什么建议吗?
Use this code.使用此代码。
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.