2
Hello, I have to create a dynamic query based on the following scenario in a RESTFUL application using Springboot and JPA (I am using Jpaspecificationexecutor):
I have two entity classes (Entity), the first one is products:
Produto
Long id;
String descricaoDetalhada;
List<Categoria> categorias;
And the second is related to category:
Categoria
Long id;
String nome;
As you can see, a product can have several categories.
I have an endpoint with two parameters: Descricao and Categorias.
Below I am sending the code of the Specification class where I need to create the second Predicate to perform the filter by categories, because the filter by description is already ready.
    public class ProdutoSpecification implements Specification<Produto>{
            private static final long serialVersionUID = 1L;
            private String descricao;
            private String categorias;
            List<Predicate> predicates = new ArrayList<>();
            public ProdutoSpecification(String descricao, String categorias) {
                super();
                this.descricao = descricao;
                this.categorias = categorias;
            }
            @Override
            public Predicate toPredicate(Root<Produto> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                if (descricao != null) {
                    String PalavraChave[] = descricao.split(" ");
                    //Predicate para o filtro por descrição
                    for (String filtro : PalavraChave) {
                        predicates.add(builder.like(builder.upper(root.get("descricaoDetalhada")), "%"+ filtro.toUpperCase() + "%"));
                    }
                }
                //Predicate para o filtro por categorias
                if (categorias != null) {
                    List<Long> ids = URL.decodeLongList(categorias);
                //AQUI DEVERÁ TER A INSTRUÇAO QUE CRIA O PREDICATE ONDE VERIFICA SE UM CÓDIGO DE CATEGORIA É PRESENTE EM ALGUM PRODUTO.
                }
                return builder.and(predicates.toArray(new Predicate[0]));
            }
        }
The variable categories in the class is transformed into a List<Long> ids. 
How to create a Predicate where I check if one of the categories present in the product is within the ids thus meeting the query parameter? So I could filter the products that have certain categories.
The commented region in the code will receive the instruction for creating the Predicate.
Sincerely yours,
Gonzaga
Weslley, I spent the whole night trying to find this solution, it was perfect. Thank you very much.
– Gonzaga Neto
Blz, good luck to you!
– Weslley Barbosa