缺少父母的春季休息子资源请求

时间:2018-11-20 18:27:43

标签: rest spring-boot

我有一个 User 实体和一个 Post 一对一关系。要获取用户资源,我在 UserController

中对此端点发出GET请求:
http://localhost:8080/users/{userId}

如果请求的userId与MySQL中的用户不对应,我会通过 UserService 类(下面的代码)抛出404 User not found错误,并引发异常。

public User getUser(Integer id) throws ResourceNotFoundException{
    return userRepository.findById(id).map(user -> {
        return user;
    }).orElseThrow(() -> new ResourceNotFoundException("User with the ID " + id + " is not available"));
}

现在为了获取 Post 资源,我在 PostController 上使用此终结点:

http://localhost:8080/users/{userId}/posts/{postId}

我的问题:如果我请求不存在的用户发帖(无论是什么)怎么办?再次抛出404用户未找到错误或发布未找到的最佳逻辑是吗?如果是这样,我如何结合UserService getUser(id)和PostService getPost(id)来引发错误?

1 个答案:

答案 0 :(得分:0)

实际上,这取决于您如何映射用户和帖子之间的关系。

如果是双向关系且级联类型为ALL,则在删除用户时,该用户创建的所有帖子也会被删除。

因此,如果是上述情况,那么您只需在DB中检查用户(如果找不到),然后显示未找到用户即可。

此外,您还应该执行建议的方法,以使用soft delete删除用户