I have a question about CriteriaBuilder API. I am new in JPA, I would like to create a count(*) thought a 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();
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.