【问题标题】:Entry creation returns a 201 but accessing it returns 404条目创建返回 201,但访问它返回 404
【发布时间】:2017-10-21 12:43:41
【问题描述】:

我有一个简单的 Spring Data Rest 使用 HibernateMongoDB 实现用户创建。

User.java

@Data
@Entity
@RequiredArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class User {

    private @Id String username;

    private String about;
}

UserRepository.java

@PreAuthorize("hasRole('ROLE_USER')")
@CrossOrigin(methods = {GET, PUT, POST})
public interface UserRepository extends MongoRepository<User, String> {

    @Override
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    <S extends User> S save(S s);
}

然后我用这个正文向/users 发出 POST 调用:

{
    "username": "username1",
    "about": "example"
}

我收到201 Created 回复,正文如下:

{
    "about": "example",
    "_links": {
        "self": {
            "href": "http://localhost:8080/api/users/username1"
        },
        "user": {
            "href": "http://localhost:8080/api/users/username1"
        }
    }
}

我向/users 发出GET 请求,以查看是否确实添加了该用户,并且此响应正确返回,因此:

{
    "_embedded": {
        "users": [
            {
                "about": "example",
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/api/users/username1"
                    },
                    "user": {
                        "href": "http://localhost:8080/api/users/username1"
                    }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/api/users{?page,size,sort}",
            "templated": true
        },
        "profile": {
            "href": "http://localhost:8080/api/profile/users"
        }
    },
    "page": {
        "size": 20,
        "totalElements": 1,
        "totalPages": 1,
        "number": 0
    }
}

问题

然后我访问了链接中提供的用户的 URL,即http://localhost:8080/api/users/username1,但我得到了404 Not Found 响应。

我做错了什么?我尝试过查看示例和文档,但似乎没有任何效果。如果我添加 @AutoGenerated 注释它可以工作,但我显然希望 id 由请求提供为 username

【问题讨论】:

    标签: spring mongodb hibernate spring-boot spring-data-rest


    【解决方案1】:

    User.java 中,我将username 的声明更改为:

    @Id
    @JsonProperty("username")
    @NotBlank
    private String id;
    

    默认情况下,MongoDb 要求 _id 作为每个文档的主键,否则它不会被索引。我必须将字段名称更改为 id 以便它在 MongoDB 上使用 @Id 注释转换为 _id。为了在消费者端解决这个问题,我使用 @JsonProperty("username") 从请求的 JSON 正文的 username 属性中获取值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多