Home > Mobile >  How to create filters in Spring boot based on a List
How to create filters in Spring boot based on a List

Time:10-19

I have to created filters data in spring boot. From frontEnd, I am sending a list containing the selected id of each category.I need to return items based on this list. I can do it this way

Service:

    public List<ProductModel> getProductFilter(Integer[] categories) {
        int size = categories.length;

        if(size == 1){
            return productRepository.getProductFilteredByOneCategory(Long.valueOf(categories[0]));
        }else {
            return productRepository.getProductFilteredByTwoCategory(Long.valueOf(categories[0]),Long.valueOf(categories[1]));
        }
    }
}

Repository:

@Query("SELECT c FROM ProductModel c WHERE c.categoryModel.id = :Category_id")
List<ProductModel> getProductFilteredByOneCategory(Long Category_id);

@Query("SELECT c FROM ProductModel c WHERE c.categoryModel.id = :Category_idOne OR c.categoryModel.id = :Category_idTwo")
List<ProductModel> getProductFilteredByTwoCategory(Long Category_idOne, Long Category_idTwo);

But if there are 50 of these categories, it is useless. Can anyone tell me how to make it better? There is some way to generate a query from a list?

CodePudding user response:

You can use in instead of using multiple or operations as follows. It select all productModels match any categoryModel id in List.

@Query("SELECT c FROM ProductModel c WHERE c.categoryModel.id in category_ids")
List<ProductModel> getProductFilteredByCategoryIds(List<Long> Category_ids);

CodePudding user response:

As @YJR said, IN clause is the solution, but you should also consider declaring query method as shown below, which doesn't require writing JPQL.

public List<ProductModel> findByCategoryModel_IdIn(List<Long> categoryIds);
  • Related