Created
August 12, 2023 14:45
-
-
Save Francisco-Castillo/c183adc16e66612897f9637852be8348 to your computer and use it in GitHub Desktop.
FindAll Jpa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @param page | |
* @param size | |
* @param search | |
* @param orderBy | |
* @param orientation | |
* @param includeInactive | |
* @return | |
*/ | |
public ResponseEntity<Object> findAll(int page, int size, String search, | |
String orderBy, String orientation, Boolean includeInactive) { | |
String msg; | |
try { | |
PageRequest pageRequest = PageRequest.of(page, size); | |
Page<Paciente> pacientePage; | |
pacientePage = pacienteRepository.findAll(new Specification<Paciente>() { | |
@Override | |
public Predicate toPredicate(Root<Paciente> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { | |
List<Predicate> predicates = new ArrayList<>(); | |
// Buscamos por apellido, nombre o dni | |
if (search != null && !search.isEmpty()) { | |
predicates.add(cb.or( | |
cb.like(cb | |
.lower(root.get(FIELD_PERSON).get(FIELD_LASTNAME)), "%" + search.toLowerCase() + "%"), | |
cb.like(cb | |
.lower(root.get(FIELD_PERSON).get(FIELD_NAME)), "%" + search.toLowerCase() + "%"), | |
cb.like(cb | |
.lower(root.get(FIELD_PERSON).get(FIELD_IDENTIFICATION)), "%" + search.toLowerCase() + "%")) | |
); | |
} | |
if (includeInactive == null || includeInactive == false) { | |
predicates.add(cb.and(cb.equal(root.get(FIELD_STATUS), ACTIVE))); | |
} | |
// Ordenamos | |
if (orderBy != null && !orderBy.isEmpty()) { | |
if (orientation != null && !orientation.isEmpty()) { | |
cq.orderBy(orientation.equals("asc") | |
? cb.asc(root.get(FIELD_PERSON).get(orderBy)) | |
: cb.desc(root.get(FIELD_PERSON).get(orderBy))); | |
} | |
} else { | |
cq.orderBy(cb.asc(root.get(FIELD_PERSON).get(FIELD_LASTNAME))); | |
} | |
return cb.and(predicates.toArray(new Predicate[predicates.size()])); | |
} | |
}, pageRequest); | |
List<PacienteDTO> listDTO = PacienteMapper.INSTANCE.toListDTO(pacientePage.getContent()); | |
Map<String, Object> response = new HashMap<>(); | |
response.put("pacientes", listDTO); | |
response.put("currentPage", pacientePage.getNumber()); | |
response.put("totalItems", pacientePage.getTotalElements()); | |
response.put("totalPages", pacientePage.getTotalPages()); | |
return new ResponseEntity<>(response, HttpStatus.OK); | |
} catch (Exception e) { | |
msg = String.format("Ocurrio un error al intentar obtener listado de pacientes." | |
+ " Excepcion: %s", | |
e.getLocalizedMessage()); | |
log.error(msg); | |
return new ResponseEntity<>(msg, HttpStatus.INTERNAL_SERVER_ERROR); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment