package persistence.specifications;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;
import persistence.models.Product;
import persistence.models.Product_;
import web.models.FilterProduct;

/**
 *
 * @author sergio
 */
public class ProductFilterSpecification implements Specification<Product>{
   
    private FilterProduct filterProduct;

    public ProductFilterSpecification(FilterProduct filterProduct) {
        this.filterProduct = filterProduct;
    }
   
    @Override
    public Predicate toPredicate(Root<Product> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();
        // filter for product price from
        if(filterProduct.getPriceFrom() != null){
            predicates.add(cb.greaterThanOrEqualTo(root.get(Product_.price), filterProduct.getPriceFrom()));
        }
        // filter for product price to
        if(filterProduct.getPriceTo() != null){
            predicates.add(cb.lessThanOrEqualTo(root.get(Product_.price), filterProduct.getPriceTo()));
        }
        return andTogether(predicates, cb);
    }
    
    private Predicate andTogether(List<Predicate> predicates, CriteriaBuilder cb) {
        return cb.and(predicates.toArray(new Predicate[0]));
      }
}

@@ -906,35 +906,207 @@
       // filter 
-for
+by product id%0D%0A        if(filterProduct.getId() != null)%7B%0D%0A            predicates.add(cb.equal(root.get(Product_.id), filterProduct.getId()));%0D%0A        %7D%0D%0A        // filter by
  product price f
@@ -1304,11 +1304,10 @@
 ter 
-for
+by
  pro
@@ -1362,32 +1362,32 @@
 To() != null)%7B%0D%0A
-
             pred
@@ -1478,32 +1478,431 @@
 ));%0D%0A        %7D%0D%0A
+        // filter by name%0D%0A        if(filterProduct.getName() != null && !filterProduct.getName().isEmpty())%7B%0D%0A            predicates.add(cb.like(root.get(Product_.name), %22%25%22+filterProduct.getName()+%22%25%22));%0D%0A        %7D%0D%0A        // filter by status%0D%0A        if(filterProduct.getStatus() != null)%7B%0D%0A            predicates.add(cb.equal(root.get(Product_.status), filterProduct.getStatus()));%0D%0A        %7D%0D%0A
         return a

improve product filter