Querying in a List (IN) - Predicate and Specification - JPA CriteriaBuilder

1
Hello, I have to create a dynamic query based on the following scenario in a RESTFUL application using Springboot and JPA (I'm using JpaSpecificationExecutor):

I have two entity classes (Entity), the first is that of products:

Produto
Long id;
String descricaoDetalhada;
List<Categoria> categorias;

And the second one refers to the 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 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 category variable in the class is transformed into a List<Long> ids.

How do I create a Predicate where I check if one of the categories present in the product is inside the ids thus meeting the query parameter? So I could filter products that have certain categories.

The commented region in the code will receive the Predicate build statement.

Sincerely,

Gonzaga

    
asked by anonymous 06.05.2018 / 20:23

1 answer

2
    Long[] tipos = URL.decodeLongList(categorias);
    if (tipos!=null) {
        predicates.add(root.join("categorias").get("id").in(tipos));
    }
    
07.05.2018 / 15:41