Spring-Boot RestController:将 Id 作为字符串传递不起作用

问题描述

我将 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> {

}

数据库获取所有歌曲信息工作正常:

Postman_1

但是当从这些条目之一传递 id 时,我得到了这个:

enter image description here

我的实现有什么问题?

解决方法

您在 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);
    }
}
,

我认为您需要将两个问题分开。

  1. 检查id参数SongsInfoController
    内部控制器通过日志或系统输出检查您的参数是否有效

  2. 检查getSongInfoById中的SongInfoServiceImpl方法
    只是 getSongInfoById(8752); 是得到错误?

我想添加评论,但我的声誉低于 50。
如果您评论以上两个解决方案检查结果,那么我将添加其他答案。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...