关于实现搜索过滤器的建议,该过滤器在两个对象之间具有许多 2many 关系



我想实现/search rest 方法,该方法将筛选我的 Product 对象以查找给定参数,并返回一组可分页的已筛选产品。

我正在阅读有关规范接口和标准 API 的信息,但在实施解决方案时遇到困难。

产品实体:

@Entity
public class Product implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long productId;
    @NotEmpty(message = "The product name must not be null.")
    private String productName;
    private String productDescription;
    @Min(value = 0, message = "The product price must no be less then zero.")
    private double productPrice;
    @Min(value = 0, message = "The product unit must not be less than zero.")
    private int unitInStock;
    @ManyToMany
    @JoinTable(name = "category_product", joinColumns = @JoinColumn(name = "product_id"), inverseJoinColumns = @JoinColumn(name = "category_id"))
    private Set<Category> categories = new HashSet<>();

由于我希望用户也能够按类别名称进行搜索,因此价格范围和单位库存是独立的实体,并且与@ManyToMany关系相关联,因此我希望有一个看起来像这样的方法:


@GetMapping("/search")
    public ResponseEntity<Set<Product>> advancedSearch(@RequestParam(name="category") String categoryName,
                                                       @RequestParam(name="price") double price,
                                                       @RequestParam(name="unitInStock") int unitInStock  ){
    }

类别实体:

@Entity
public class Category implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long categoryId;
    @NotEmpty(message = "Can not be null")
    private String CategoryName;
    @ManyToMany(mappedBy = "categories")
    @JsonBackReference
    private Set<Product> products = new HashSet<>();

使用带有JPQL查询的方法创建弹簧存储库:

@Query("select p from Product p left join p.categories c where c.CategoryName like ?1 and p.productPrice=?2 and p.unitInStock=?3")
List<Product> search(String categoryName, double price, int unitInStock)

最新更新