目前我有一个使用Spring Data REST的Spring Boot应用程序。我有一个与另一个域实体Post有@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应用程序。一切都是配置库存。
Application.java
@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
一切似乎都正常。当我运行应用程序时,一切似乎都正常工作。我可以POST一个新的Post对象http://localhost:8080/posts:
身体: {"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我得到一个空对象{}返回,如果我尝试将注释POST到同一个URI,我得到一个HTTP 405方法不允许。
创建Comment资源并将其与此关联的正确方法是什么Post?http://localhost:8080/comments如果可能的话,我想避免直接POST 。
狐的传说
富国沪深
白板的微信