目前,我有一个使用Spring Data REST的Spring Boot应用程序。我有一个域实体Post,它@OneToMany与另一个域实体有关系Comment。这些类的结构如下:
@OneToMany
Comment
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应用程序。一切都已配置库存。
应用程序
@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就像这样:
过程: {"author":"testAuthor", "title":"test", "content":"hello world"}
{"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发表评论,则会收到HTTP 405方法不允许。
创建Comment资源并将其与此关联的正确方法是什么Post?http://localhost:8080/comments如果可能,我想避免直接过帐。
Post
应该像下面这样:
http://{server:port}/comment METHOD:POST {"author":"abc","content":"PQROHSFHFSHOFSHOSF", "post":"http://{server:port}/post/1"}