我想实现/ 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关系链接,因此我希望有一个类似于以下内容的方法:< / p>
@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<>();
答案 0 :(得分:0)
使用带有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)