【问题标题】:Apply price filter in JPA query在 JPA 查询中应用价格过滤器
【发布时间】:2020-10-11 18:10:59
【问题描述】:

我正在使用 Spring Boot JPA。我想按产品的低价过滤结果。该查询在不涉及价格属性的情况下工作正常,但是当我按价格添加过滤器时,它会给出一个空列表。但是,该查询在 MySQL 工作台中运行并给出了适当的结果。 有人可以帮助解决这个问题,为什么我得到一个空的结果?

存储库:

@Query("SELECT new com.example.demo.model.CustomerProductDTO(vp.vendorproductid, p.name, vp.price, CASE quantitykg WHEN NULL THEN vp.quantitybundle ELSE vp.quantitykg END, p.image) FROM vendorproduct vp JOIN vp.product p ON p.productid = vp.productid WHERE vp.vendorid=:vendorid AND vp.price>=:minprice AND vp.price<=:maxprice ORDER BY vp.price")
    
List<CustomerProductDTO> getProductsLowToHigh(String vendorid, float minprice, float maxprice, Pageable p);

控制器:

@GetMapping("/products/{vendorid}")
public List<CustomerProductDTO> getCustomerProducts(@PathVariable("vendorid") String vendorid,
    @RequestParam Map<String, String> map) {

    List<CustomerProductDTO> customerProductDTOs = new ArrayList<CustomerProductDTO>();
    Pageable p = PageRequest.of(0, 10);

    if (map.get("minprice").equals("null") && map.get("maxprice").equals("null")) {
        customerProductDTOs = vendorProductRepo.getProductsLowToHigh(vendorid, p);
    }
    else {
        Float minPrice = Float.valueOf(map.get("minprice"));
        Float maxPrice = Float.valueOf(map.get("maxprice"));

        customerProductDTOs = vendorProductRepo.getProductsLowToHigh(vendorid, minPrice, maxPrice, p);
    }       
    return customerProductDTOs;
}

返回的 DTO:

public class CustomerProductDTO {
    
    int vendorproductid;
    String name;
    float price;
    int quantity;
    String image;    
    int stockQuantity;    
    boolean isOutOfStock;

        public CustomerProductDTO() {}
        public CustomerProductDTO(int vendorproductid, String name, float price, int quantity, String image) {
        super();
        this.vendorproductid = vendorproductid;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
        this.image = image;
    }

    //getter and setter
}

【问题讨论】:

  • 您尝试调用的确切查询是什么(参数值是什么)? BTW float 不完全是适合存储货币值的数据类型。我强烈建议改用BigDecimal
  • 我已经提到了所有问题。好的,谢谢您的建议。
  • 能否添加实体类?

标签: mysql spring spring-boot jpa spring-data-jpa


【解决方案1】:

在线上方的控制器中,

customerProductDTOs = vendorProductRepo.getProductsLowToHigh(vendorid, minPrice, maxPrice, p)

添加下面给出的代码,以便此注释可以帮助您按升序或降序对收到的记录进行排序,并且您还可以提及要排序的确切字段。

@ElementCollection
@OrderBy("position.code DESC")

【讨论】:

    猜你喜欢
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多