public List getProdutos(String nome, Integer categoriaId, Integer lojaId) { CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery query = criteriaBuilder.createQuery(Produto.class); Root root = query.from(Produto.class);
Path<String> nomePath = root.<String> get("nome");
Path<Integer> lojaPath = root.<Loja> get("loja").<Integer> get("id");
Path<Integer> categoriaPath = root.join("categorias").<Integer> get("id");
List<Predicate> predicates = new ArrayList<>();
if (!nome.isEmpty()) {
Predicate nomeIgual = criteriaBuilder.like(nomePath,nome);
predicates.add(nomeIgual);
}
if (categoriaId != null) {
Predicate categoriaIgual = criteriaBuilder.equal(categoriaPath, categoriaId);
predicates.add(categoriaIgual);
}
if (lojaId != null) {
Predicate lojaIgual = criteriaBuilder.equal(lojaPath, lojaId);
predicates.add(lojaIgual);
}
query.where((Predicate[]) predicates.toArray(new Predicate[0]));
TypedQuery<Produto> typedQuery = em.createQuery(query);
return typedQuery.getResultList();