Skip to content

Instantly share code, notes, and snippets.

@igor-rodrigues2017
Created April 30, 2019 13:38
Show Gist options
  • Save igor-rodrigues2017/245810565a23de7d53d5f630dfd3c636 to your computer and use it in GitHub Desktop.
Save igor-rodrigues2017/245810565a23de7d53d5f630dfd3c636 to your computer and use it in GitHub Desktop.
/**
* List filtered Bovines
*
* @param id
* @param sex
* @param type
* @param nick
* @return
*/
public List<Bovine> listarBovinos(Integer id, Sex sex, BovineType type, String nick) {
CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
CriteriaQuery<Bovine> query = criteriaBuilder.createQuery(Bovine.class);
Root<Bovine> root = query.from(Bovine.class);
Path<Integer> pathId = root.get("id");
Path<Sex> pathSex = root.get("sex");
Path<BovineType> pathType = root.get("type");
Path<String> pathNick = root.get("nick");
Path<StatusAnimal> pathStatus = root.get("status");
Predicate conjunction = criteriaBuilder.conjunction();
conjunction = criteriaBuilder.and(criteriaBuilder.equal(pathStatus, StatusAnimal.ACTIVE));
if (id != null) {
Predicate IdIgual = criteriaBuilder.equal(pathId, id);
conjunction = criteriaBuilder.and(IdIgual);
}
if (sex != null) {
conjunction = criteriaBuilder.and(criteriaBuilder.equal(pathSex, sex));
}
if (type != null) {
conjunction = criteriaBuilder.and(criteriaBuilder.equal(pathType, type));
}
if (nick != null && !nick.isEmpty()) {
conjunction = criteriaBuilder.and(criteriaBuilder.like(pathNick, "%" + nick + "%"));
}
TypedQuery<Bovine> typedQuery = manager.createQuery(query.where(conjunction));
return typedQuery.getResultList();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment