【发布时间】:2019-06-25 09:51:20
【问题描述】:
我正在做一个项目(基本商店),目前我坚持订购(例如按价格、名称等)。我想知道是否有任何简单的方法可以针对我的商品使用 order by 对许多情况进行 1 次灵活查询。因为我的代码会返回无序列表的对象。
所以在这个项目中,我在用户在组合框元素中选择排序类型后向服务器发送请求。之后我的控制器选择排序方式,它调用查询,然后返回我们的对象。
请帮忙,有机会你能告诉我在控制器或服务实现中哪种方式的 switch(order_type) 更好?
附:如果我以 [http://localhost:9999/commodities/category-name/CPU/c.name%20asc] 控制器的身份向服务器发送请求,我会使用 switch 原因,只看到没有 .name asc 的 c,这就是我使用 switch 的原因。
代码:
控制器:
@RestController
@RequestMapping("commodities")
public class CommodityController {
@GetMapping("category-name/{name}/{order_type}")
public ResponseEntity<List<CommodityDTO>> getCommodityByCategoryNameWithOrder(@PathVariable("name") String categoryName, @PathVariable("order_type") String order_type){
List<CommodityDTO> byCategoryWithOrder;
switch(order_type) {
case "name_asc":
byCategoryWithOrder = commodityService.getAllByCategoryNameWithOrder(categoryName, "c.name asc");
break;
case "name_desc":
byCategoryWithOrder = commodityService.getAllByCategoryNameWithOrder(categoryName, "c.name desc");
break;
case "price_asc":
byCategoryWithOrder = commodityService.getAllByCategoryNameWithOrder(categoryName, "c.price asc");
break;
case "price_desc":
byCategoryWithOrder = commodityService.getAllByCategoryNameWithOrder(categoryName, "c.price desc");
break;
default:
return null;
}
return new ResponseEntity<List<CommodityDTO>>(byCategoryWithOrder,HttpStatus.OK);
}
服务实现:
@Service
@Transactional
public class CommodityServiceImpl implements CommodityService{
@Autowired
private CommodityRepository commodityRepository;
@Autowired
private ObjectMapperUtils objectMapperUtils;
@Autowired
private CloudinaryService cloudinaryService;
@Override
public List<CommodityDTO> getAllByCategoryNameWithOrder(String categoryName, String order_type){
System.out.println("\n\n\n\nOrder type:\n"+order_type+"\n\n\n\n");
return objectMapperUtils.mapAll(commodityRepository.findAllByCategoryNameWithOrder(categoryName, order_type), CommodityDTO.class);
}
}
存储库:
public interface CommodityRepository extends JpaRepository<Commodity, Integer>{
@Query("Select c FROM Commodity c "
+ "Join Category ct on c.category.id = ct.id "
+ "where ct.name = ?1 "
+ "order by ?2")
List<Commodity> findAllByCategoryNameWithOrder(String categoryName, String order_type);
}
【问题讨论】:
-
首先,排序应该在前端而不是服务器端执行,因此您将保存数据库调用,即您只需将数据提供给前端并且排序应该在客户端完成,如果有一些逻辑变化或存在大量数据,那么排序数据然后在服务器端排序是好的,在这种情况下也可以获取数据并使用 java 逻辑来排序而不是 DB 逻辑跨度>
-
不要编写自己的查询。只需添加
findByCategoryName(String name, Pageable pageable)。在Pageable你可以指定你想要的尺寸和顺序。 -
@AyushGoyal 在客户端排序是否正确?因为如果我们模拟一种情况,例如我们有 1000 种不同价格的产品,而我们使用页面仅请求 20 种产品(这始终是更好的用户体验所必需的),根据您的建议,我们将仅在 20 种范围内进行排序我们从第一次获取请求中获得的元素。因此,如果我们按价格排序,我们实际上不会得到最贵的一个,或者是我们商店中最便宜的,而是我们从页面请求中获得的 20 个对象中的一个。为了避免这种情况,我们需要使用 order by 或 SortedSet 集合发出请求。
-
@Yurii Malskiy 正确,我的错!!
标签: java spring jpa spring-data-jpa spring-data