【发布时间】: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