Query with multiple Ids and date with JPA and Spring via RESTApi

0

Good morning, I'm trying to set up an appointment with Spring JPA and Rest where I can insert several IDs and datainicial and datafinal. The query works if I only put an ID with the dates. The code looks like this:

@GetMapping("/search")
public List<TagsDay> pesquisar(@RequestParam(value = "ids") List<Long> ids, TagsDayFilter tagsDayFilter){
    return tagsDayRepository.filtrar(ids, tagsDayFilter);
}

Interface:

public interface TagsDayRepositoryQuery {

    public List<TagsDay> filtrar(List<Long> ids, TagsDayFilter tagsDayFilter);

}

and the implementation class:

public class TagsDayRepositoryImpl implements TagsDayRepositoryQuery{

    @PersistenceContext
    private EntityManager manager;

    @Override
    public List<TagsDay> filtrar(List<Long> ids, TagsDayFilter tagsDayFilter) {

        CriteriaBuilder builder = manager.getCriteriaBuilder();
        CriteriaQuery<TagsDay> criteria = builder.createQuery(TagsDay.class);

        Root<TagsDay> root = criteria.from(TagsDay.class);

        //criar as restrições
        Predicate[] predicates = criarRestricoes(ids, tagsDayFilter, builder, root);
        criteria.where(predicates);

        TypedQuery<TagsDay> query = manager.createQuery(criteria);
        return query.getResultList();
    }

    private Predicate[] criarRestricoes(List<Long> ids, TagsDayFilter tagsDayFilter, CriteriaBuilder builder, Root<TagsDay> root) {

        List<Predicate> predicates = new ArrayList<>();     

        if(ids.size() > 0) {

            for(int i = 0; i < ids.size(); i++) {
                predicates.add(builder.equal(root.get("id"), ids.get(i)));  //adiciona vários ids para consulta         
            }


        }
        if(tagsDayFilter.getDataInicial() != null) {
            predicates.add(builder.greaterThanOrEqualTo(root.get("data_coleta"), tagsDayFilter.getDataInicial()));
        }
        if(tagsDayFilter.getDataFinal() != null) {
            predicates.add(builder.lessThanOrEqualTo(root.get("data_coleta"), tagsDayFilter.getDataFinal()));
        }

        return predicates.toArray(new Predicate[predicates.size()]);
    }



}

and in the URL I do: localhost:8080/tagsday/search?ids=1,2&dataInicial=2018-09-27&dataFinal=2018-09-28

    
asked by anonymous 02.10.2018 / 16:50

0 answers