0
Good morning, I’m trying to set up a query with Spring JPA and Rest where I can insert several Ids and initial and final date. The query works if I only put an ID with the dates. The code is 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 do: localhost:8080/tagsday/search?ids=1,2&dataInicial=2018-09-27&dataFinal=2018-09-28
What is the error? Put in the description of the question.
– Giuliana Bezerra
It doesn’t make any mistakes, it just doesn’t return anything. The query was generated this way: select tagsday0_.id as id1_2_, tagsday0_.data_collects as data_col2_2_, tagsday0_.tags_id as tags_id4_2_, tagsday0_.value as valor3_2_ from tags_day tagsday0_ Where tagsday0_.id=1 and tagsday0_.id=2 and tagsday0_.data_collection>=? and tagsday0_.data_collection<=?
– Ronaldo Lopes
Ever tried to use
@Query
, setting up a custom query? Something like@Query("SELECT t FROM TagsDay t WHERE t.id IN (?1) AND (t.data BETWEEN ?2 AND ?3)")
, where 1 is the list, 2 would be the initial date and 3 the final date. Take a look at here– StatelessDev
Good morning, so I would like to keep it that way because I need to understand how it works, via normal SQL would be very easy. One thing I realized is that if instead of the query generating an AND, the same was by OR would work. It is possible to make this change?
– Ronaldo Lopes