我正在尝试使用Spring Boot从基于多个ID的数据库中的多个数据中获取数据。
基本上,这是一个GET调用,它将请求参数作为ID列表,并相应地返回响应。 ID在数据库中是唯一的
Url : api/details/1a,2a,3b
我得到的回应是:
Get(value = "api/details/{Ids})
{
[id="1a",name="Raj", interest="Football"],
[id="2a",name="Tom", interest="Cricket"]
[id="3b",name="Kane", interest="Baseball"]
}
没事。但是,当我输入错误的ID时,我得到的响应为:
Url : api/details/xyz,abc,3b
{
null,
null,
[id="3b",name="Kane", interest="Baseball"]
}
我希望它显示null而不是ID而不是状态代码。就像是
{
2-Not found,3-Not Found,
id="3b",name="Kane", hobby="Baseball,
}
我的控制器类是这样的:
@RequestMapping(value = "api/details{Ids}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Game>>
getMultipleDetails(@PathVariable("Idss") String Idss) {
HttpHeaders headers = new HttpHeaders();
List<String> ids = Arrays.asList(Idss.split(","));
List<Game> list = new ArrayList<>();
Game details= null;
for (String id : ids) {
details= da.getMultipleDetails(id);
list.add(devices);
}
if (details== null) {
throw new RuntimeException(HttpStatus.NOT_FOUND.toString());
}
return new ResponseEntity<List<Game>>(list, headers, HttpStatus.OK);
}
}
我的存储库类是这样的:
public Device getMultipleDetails(String id) {
Game details= null;
try {
details= jdbcTemplate.queryForObject("SELECT * FROM table_name WHERE Id = ?",new DeviceRowMapper(), id);
} catch (Exception e) {
// Log the system generated Id
String systemRefId = String.valueOf(System.currentTimeMillis());
LOGGER.error(systemRefId, e);
//throw new DatabaseException(systemRefId, e);
}
return details;
}
游戏是我的模型课程,包含ID,名称,爱好
最佳答案
您应该管理空对象,并管理消息,代码应该是这样的,因为如果没有,则只有最后一个详细信息被评估,这就是为什么不引发异常的原因。
for (String id : ids) {
details= da.getMultipleDetails(id);
list.add(devices);
if (details== null) {
throw new RuntimeException(HttpStatus.NOT_FOUND.toString());
}
}