【发布时间】:2020-10-15 12:51:58
【问题描述】:
您好,最近我一直在研究 REST API。 我想知道如果没有参数,如何获取所有数据。 我只能通过 categoryId 获取数据,如下所示。 http:// .... /categorys?categoryId=2 数据是这样选择和显示的。
{
"items": [
{
"id": 2,
"name": "music",
"count": 20
}
]
}
但我也想获取所有没有参数的数据,如下所示 => http:// .... /类别
{
"items": [
{
"id": 1,
"name": "movie",
"count": 10
},
{
"id": 2,
"name": "music",
"count": 20
},
{
"id": 3,
"name": "book",
"count": 16
}
]
}
这是该类别数据的mysql查询
SELECT_CATEGORYS = "SELECT category.id as id, category.name as name, count(*) as count FROM product inner join category where product.category_id = category.id group by category.id, category.name;"
这是 CategoryApiController.java
@RestController
@RequestMapping(path="/categorys")
public class CategoryApiController {
@Autowired
ReservationService reservationService;
@GetMapping
public Map<String, Object> categorys(@RequestParam(name="categoryId", required=false, defaultValue="0") int categoryId) {
List<Categorys> list = reservationService.getCategorys(categoryId);
Map<String, Object> map = new HashMap<>();
map.put("item", list);
return map;
}
}
请帮我解决这个问题。 提前致谢。 路径不应该改变,我需要保留这个 getmapping /categorys 所以没有参数它应该是 /categorys 和参数,它应该是这样的 /categories?categoryId = 2
【问题讨论】: