0

I am coding a searching so I am using Specification to do it.

I have a relationchip beetwin tow tables (ManytoMany) like this:

public class Productos implements Serializable {
.
.
.
@JoinTable(name = "PRODUCTOS_CATEGORIAS", joinColumns = {
    @JoinColumn(name = "PRODUCTOS_PROD_ID", referencedColumnName = "PROD_ID")}, inverseJoinColumns = {
    @JoinColumn(name = "CATEGORIAS_CATE_ID", referencedColumnName = "CATE_ID")})
@ManyToMany
private Collection<Categorias> categoriasCollection;

The data I have it the "CATE_ID" tha id in "Categoria" is call "cateId".

I need to know how to build the criteriaBuilder to add to the predicates in the previous case when I have manyToMany relationchip.

This is my code:

public class ProductosSpecification {

public Specification<Productos> getProductos(BuscaProductosDto buscaProductosDto) {
    
    return (root, query, criteriaBuilder) -> {

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

        if (buscaProductosDto.getCategoria() != null && buscaProductosDto.getCategoria() != 0) {
            ------ HERE IS WHEN I NEED TO DO THE RIGHT WAY WHEN IS MANYTOMANY
            Join<Productos, Categorias> join = root.join("categoriasCollection", JoinType.INNER);
            predicates.add(criteriaBuilder.equal(join.get("name").as(String.class), buscaProductosDto.getCategoria()));
          
            predicates.add(criteriaBuilder.equal(root.get("categoriasCollection").get("cateId"), buscaProductosDto.getCategoria()));
                   ------------------  

        }
        if (buscaProductosDto.getValorDesde() != null && buscaProductosDto.getValorHasta() != null && buscaProductosDto.getValorHasta() != 0) {
            predicates.add(criteriaBuilder.between(root.get("prodValor"), buscaProductosDto.getValorDesde(), buscaProductosDto.getValorHasta()));
                            
        }
        if (buscaProductosDto.getLocalidad()!= null && buscaProductosDto.getLocalidad()!= 0) {
            predicates.add(criteriaBuilder.equal(root.get("emprId").get("locaId").get("locaId"), buscaProductosDto.getLocalidad()));
        }
        if (buscaProductosDto.getAglomeracion()!= null && buscaProductosDto.getAglomeracion()!= 0) {
            predicates.add(criteriaBuilder.equal(root.get("emprId").get("agloId").get("agloId"), buscaProductosDto.getAglomeracion()));
        }

        query.orderBy(criteriaBuilder.desc(root.get("experience")));

        return criteriaBuilder.and(predicates.toArray(new Predicate[0]));

    };
    
    
}

}

I will apresiate your help.

  • Might be a duplicate of this https://stackoverflow.com/questions/8135612/jpa-criteria-for-many-to-many-relationship – ALex Nov 03 '22 at 12:38

0 Answers0