我正在嘗試使用@RequestParam,如果給定了該值,它應該通過此引數從資料庫中找到的所有專案中進行過濾,否則它什么都不做。我還想問一下,函式式編程在這里是否有用。
這是我的汽車課:
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
import javax.persistence.*;
@Data
@Entity
@Table(name = "Cars")
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Setter(AccessLevel.NONE)
private Long Id;
private int yearOfProduction;
private int price;
private String color;
private String brand;
private String model;
@ManyToOne
@JoinColumn(name = "customer")
private Customer customer;
public Car() {
}
public Car(int yearOfProduction, int price, String color, String brand, String model) {
this.yearOfProduction = yearOfProduction;
this.price = price;
this.color = color;
this.brand = brand;
this.model = model;
}
}
這是我設定要請求的引數的控制器:
@GetMapping
public List<Car> getCars(@RequestParam(required = false) Integer minPrice,
@RequestParam(required = false) Integer maxPrice,
@RequestParam(required = false) String model){
return carService.getCars(minPrice, maxPrice, model);
}
這是汽車服務,我想做的是:
public List<Car> getCars(Integer minPrice, Integer maxPrice, String model) {
return carRepository
.findAll()
.stream()
.filter(car ->
//if minPrice exists
car.getPrice() >= minPrice
&&
//if maxPrice exists
car.getPrice() <= maxPrice
&&
//if model exists
car.getModel().equals(model))
.collect(Collectors.toList());
}
我可以@RequestParam (defaultValue = "something")在控制器中設定,但這是有問題的,因為我不知道“模型”欄位的默認值是什么,因為每輛汽車都有不同的模型,而且我仍然必須按默認值過濾專案,因為我不需要它如果沒有給出,我不想做任何事情。
I was also trying to pass Optional<> as the parameters and then check every parameter with if statement and ifPresent() method in filter function, but I don't how how to bring it together.
uj5u.com熱心網友回復:
您可以像這樣創建 jpa 查詢(在您的汽車存盤庫中):
@Query("select c from Car c where (?1 is null or c.price >= ?1) and (?2 is null or c.price <= ?2) and (?3 is null or c.model = ?3)")
List<Car> getCars(Integer minPrice, Integer maxPrice, String model);
然后從您的CarService:
public List<Car> getCars(Integer minPrice, Integer maxPrice, String model) {
return carRepository.getCars(minPrice, maxPrice, model);
}
在 postgresql 中規避強制轉換問題的一種方法是使用引數的默認值。假設您將 0 設定為模型的最低價格和最高價格以及空字串的默認值。
@Query("select c from Car c where (?1 = 0 or c.price >= ?1) and (?2 = 0 or c.price <= ?2) and (?3 = '' or c.model = ?3)")
List<Car> getCars(Integer minPrice, Integer maxPrice, String model);
在您的控制器中:
@RequestParam(defaultValue="") String model
@RequestParam(defaultValue="0") Integer minPrice
@RequestParam(defaultValue="0") Integer maxPrice
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351678.html
標籤:java spring spring-boot jpa functional-programming
