【发布时间】:2017-10-21 12:43:41
【问题描述】:
我有一个简单的 Spring Data Rest 使用 Hibernate 和 MongoDB 实现用户创建。
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