我已经编写了此请求映射,以使用可选请求参数ticketType&ticketStatus的ID通过票证访问票证:
@GetMapping(path = "/tickets/{ticketId}")
@ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<List<TicketResponse>> getTicketsById(@PathVariable("ticketId") final Long ticketId, @RequestParam("ticketType") final String ticketType, @RequestParam("ticketStatus") final String ticketStatus)
当前存储库包含用于基于ticketId或ticketState返回的方法:
@Repository
public interface TicketRepository extends JpaRepository<TicketEntity, Long> {
Stream<TicketEntity> findByTicketIdAndTicketState(@Param("ticketId") Long ticketId);
Stream<TicketEntity> findByTicketIdAndTicketState(@Param("ticketId") Long ticketId, @Param("ticketState") String ticketState);
}
这些端点应如何在控制器层公开?
当前端点为:
@GetMapping(path = "/{ticketId}")
@ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<List<TicketResponse>> getTicketsByTicketId(
@PathVariable("productId") final Long ticketId, @RequestParam(name = "ticketState", required=false) final String ticketState) {
final List<TicketResponse> ticketsByTicketId = ticketService.getTicketsByTicketId(ticketId);
if(ticketsByTicketId.size() == 0){
return ResponseEntity.ok("No tickets found");
}
else {
return ResponseEntity.ok(ticketsByTicketId);
}
}
我应该添加一个新的端点吗? :
或更新控制器以根据查询选择要实现的JPA存储库方法?:
@GetMapping(path = "/{ticketId}")
@ResponseStatus(value = HttpStatus.OK)
public ResponseEntity<List<TicketResponse>> getTicketsByTicketId(
@PathVariable("productId") final Long ticketId, @RequestParam(name = "ticketState", required=false) final String ticketState) {
List<TicketResponse> tickets = null;
if(ticketState == null) {
tickets = ticketService.getTicketsByTicketId(ticketId);
}
else{
tickets = ticketService.getTicketsByTicketIdAndTicketState(ticketId, ticketState);
}
if(ticketsByTicketId.size() == 0){
return ResponseEntity.ok("No tickets found");
}
else {
return ResponseEntity.ok(ticketsByTicketId);
}
}
JPA存储库将进一步扩展以基于更多的参数(例如ticketType,ticketDescription)进行过滤。我只是提到这一点,因为如果需要检查哪个参数为null并选择相关的JPA查询,我的控制器逻辑将变得非常复杂。
答案 0 :(得分:0)
使用Spring Data JPA Specification可以解决此地图过滤问题。 可以使用Criteria API构建复杂的查询,具体取决于过滤参数。