【问题标题】:Suggestion for implementation of search filter with many2many relationship between two entites在两个实体之间实现多对多关系的搜索过滤器的建议
【发布时间】:2019-08-24 16:57:05
【问题描述】:

我想实现 /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<>();

由于我希望用户也能够按类别名称搜索,除了价格范围和 unitInStock 之外,它是单独的实体,它与 @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<>();

【问题讨论】:

  • 首先,Spring 提供了多种方法来实现多对多关系,例如使用复合键类的多对多或使用新实体的多对多。根据他们的优缺点选择什么取决于您的选择。其次,当您使用 JPA 时,为什么不选择 JPQL 作为您的查询语言。这肯定会减少您的查询工作。谢谢

标签: spring rest jpa criteria specifications


【解决方案1】:

使用 JPQL 查询方法创建 spring 存储库:

@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)

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 2017-07-12
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多