[英]How to sort data in spring jpa?
I am writing my first web-application project about rental a cars in java using Spring Boot, Hibernate and MySql.我正在使用 Spring 启动、Hibernate 和 Z9DF306F03DAEDBFEB4282F3 编写我的第一个关于在 java 租车的 Web 应用程序项目。 In my app I want to have smth like sort methods.
在我的应用程序中,我希望有类似排序方法。 I made that by add in my view an input where users can type eg type or model of car.
我通过在我的视图中添加一个输入来实现这一点,用户可以在其中输入例如汽车的类型或 model。 I want to get result of query eg type='sportcar' and from this result I want to sort data eg by price DESC or ASC.
我想得到查询的结果,例如 type='sportcar' 并且我想从这个结果中对数据进行排序,例如按价格 DESC 或 ASC。
Here is my code of view这是我的视图代码
<body>
<form action="get" method="get">
<div class="form-group col-md-4">
<label for="inputState">Sort by</label>
<select name="sortMethod" id="inputState" class="form-control">
<option value="">Select sort method</option>
<option value="priceDESC">price desc</option>
<option value="priceASC">price asc</option>
</select>
<input type="submit" value="submit"/>
</div>
</form>
<form action="get" method="get">
Type: <input type="text" name="type">
<input type="submit" value="submit"/>
</form>
<form action="get" method="get">
Brand: <input type="text" name="brand"/>
<input type="submit" value="submit"/>
</form>
<form action="get" method="get">
Model: <input type="text" name="model"/>
<input type="submit" value="submit"/>
</form>
Here is my code of Controller这是我的 Controller 代码
@GetMapping(path = "/get")
public String getAllCars(ModelMap modelMap) {
cars = carRepository.findAll();
modelMap.addAttribute("cars", cars);
return "car";
}
@GetMapping(path = "/get", params = "sortMethod")
public String getAllCars(@RequestParam(defaultValue = "priceASC", required = false) String sortMethod,
ModelMap modelMap) {
String parameterOfSort = "";
String wayOfSort = "";
char c;
for (int i = 0; i < sortMethod.length(); i++) {
c = sortMethod.charAt(i);
if (c >= 64 && c <= 90)
wayOfSort += c;
else if (c >= 97 && c <= 122)
parameterOfSort += c;
}
Sort.Direction sortType = Sort.Direction.valueOf(wayOfSort);
cars = carRepository.findAll(Sort.by(sortType, parameterOfSort));
modelMap.addAttribute("cars", cars);
return "car";
}
@GetMapping(path = "/get", params = "type")
public String getCarsByType(@RequestParam String type, ModelMap modelMap) {
cars = carRepository.findCarByType(type);
modelMap.addAttribute("cars", cars);
return "car";
}
I think that my approach isn't correct.我认为我的方法是不正确的。 How can I modify my code to get satisfying result and good approach for this situation?
在这种情况下,如何修改我的代码以获得令人满意的结果和好的方法?
Check the spring jpa doc , JPA support sort, in your case:检查spring jpa doc , JPA 支持排序,在您的情况下:
public interface CarRepository extend CrudRepository<Car, Long> {
List<Car> findByTypeOrderByPriceDesc(String type); //sportsCar, order by price desc
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.