Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Query dinamica que filtra por nome e sobrenome
*
*/
public List<Pessoa> buscarPessoas(String nome, String sobrenome) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Pessoa> criteriaQuery = criteriaBuilder.createQuery(Pessoa.class);
Root<Pessoa> pessoaRoot = criteriaQuery.from(Pessoa.class);
List<Predicate> predicates = new ArrayList<>();
if(nome != null) {
predicates.add(criteriaBuilder.equal(pessoaRoot.get("nome"), nome));
}
if(sobrenome != null) {
predicates.add(criteriaBuilder.equal(pessoaRoot.get("sobrenome"), sobrenome));
}
criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
criteriaQuery.select(pessoaRoot);
TypedQuery<Pessoa> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.