问题描述
我将 Spring-Boot-Application 连接到 MongoDB。该应用程序没什么大不了的,只是为了开始使用 spring 和 MongoDB。
问题是,我的 id 是一个字符串,当我传递数据库条目的 id 以通过 Id 获取它时,我收到内部服务器错误...
这是我的域类:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(collection = "songinfo")
public class SongInfo {
@Id
private String id;
private int songId;
private String songName;
private String description;
}
控制器方法:
@requiredArgsConstructor
@RestController
@RequestMapping("/songsinfo")
public class SongsInfoController {
private final SongInfoService songInfoService;
@GetMapping(value = "/{id}",headers = "Accept=application/json",produces =
{MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<SongInfo> getSongInfoById(@PathVariable(value = "id") String id) {
SongInfo songInfo = songInfoService.getSongInfoById(id);
if (songInfo == null)
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(songInfo,HttpStatus.OK);
}
SongInfoServiceImpl:*
@Override
public SongInfo getSongInfoById(String id) {
return songInfoRepository.findById(id).orElseThrow(NotFoundException::new);
}
这是 SongsInfoRepository:
public interface SongInfoRepository extends MongoRepository<SongInfo,String> {
}
我的实现有什么问题?
解决方法
您在 SongInfoServiceImpl 中抛出了未在 SongsInfoController 类中处理的异常。
解决方案 1:而不是抛出异常返回 null。
SongInfoServiceImpl.java
@Override
public SongInfo getSongInfoById(String id) {
return songInfoRepository.findById(id).orElse(null);
}
解决方案 2:添加 try catch 块
SongsInfoController.java
@RequiredArgsConstructor
@RestController
@RequestMapping("/songsinfo")
public class SongsInfoController {
private final SongInfoService songInfoService;
@GetMapping(value = "/{id}",headers = "Accept=application/json",produces = {MediaType.APPLICATION_JSON_VALUE}
)
public ResponseEntity<SongInfo> getSongInfoById(@PathVariable(value = "id") String id) {
SongInfo songInfo = null;
try {
songInfo = songInfoService.getSongInfoById(id);
} catch(Exception e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(songInfo,HttpStatus.OK);
}
}
,
我认为您需要将两个问题分开。
-
检查
id
参数SongsInfoController
内部控制器通过日志或系统输出检查您的参数是否有效 -
检查
getSongInfoById
中的SongInfoServiceImpl
方法
只是getSongInfoById(8752);
是得到错误?
我想添加评论,但我的声誉低于 50。
如果您评论以上两个解决方案检查结果,那么我将添加其他答案。