目前我有一个使用Spring Data REST的Spring Boot应用程序。我有一个域实体Post
,它与另一个域实体Comment
具有@OneToMany
关系。这些类的结构如下:
Post.java:
@Entity
public class Post {
@Id
@GeneratedValue
private long id;
private String author;
private String content;
private String title;
@OneToMany
private List<Comment> comments;
// Standard getters and setters...
}
Comment.java:
@Entity
public class Comment {
@Id
@GeneratedValue
private long id;
private String author;
private String content;
@ManyToOne
private Post post;
// Standard getters and setters...
}
他们的Spring Data REST JPA存储库是CrudRepository的基本实现:
PostRepository.java:
public interface PostRepository extends CrudRepository<Post, Long> { }
CommentRepository.java:
public interface CommentRepository extends CrudRepository<Comment, Long> { }
应用程序的入口是一个标准、简单的Spring Boot应用程序。一切都是预配置的。
Application.java
@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
一切似乎都正常工作。当我运行应用程序时,一切似乎都正常工作。 我可以像这样将新的帖子对象POST到http://localhost:8080/posts
:
Body:
{"author":"testAuthor", "title":"test", "content":"hello world"}
结果在 http://localhost:8080/posts/1
:
{
"author": "testAuthor",
"content": "hello world",
"title": "test",
"_links": {
"self": {
"href": "http://localhost:8080/posts/1"
},
"comments": {
"href": "http://localhost:8080/posts/1/comments"
}
}
}
然而,当我执行GET请求http://localhost:8080/posts/1/comments
时,返回一个空对象{}
,如果我尝试向同一URI POST评论,则会收到HTTP 405 Method Not Allowed的错误。如何正确创建一个Comment
资源并将其与此Post
相关联?如果可能的话,我想避免直接POST到http:// localhost:8080 / comments
。