我想实现/搜索rest方法,它将过滤给定参数的Product对象,并返回一组可过滤的产品。
我正在阅读有关规范界面和Criteria 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<>();
使用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)