【发布时间】:2014-10-08 08:04:56
【问题描述】:
目前我有一个使用 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...
}
评论.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);
}
}
一切似乎都正常工作。当我运行该应用程序时,一切似乎都正常工作。我可以像这样向http://localhost:8080/posts 发布一个新的 Post 对象:
身体:
{"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"
}
}
}
但是,当我在 http://localhost:8080/posts/1/comments 执行 GET 时,我得到一个空对象 {} 返回,如果我尝试向同一个 URI 发布评论,我得到一个 HTTP 405 Method Not Allowed。
创建Comment 资源并将其与此Post 关联的正确方法是什么?如果可能的话,我想避免直接发帖到http://localhost:8080/comments。
【问题讨论】:
-
7 天后仍然没有运气。如果有人知道使这种行为起作用的方法,请告诉我。谢谢!
-
您使用的是@RepositoryRestResource 还是控制器?看看这段代码也会很有帮助。
-
我正在使用 Spring Boot 数据休息,它对我有用 http://stackoverflow.com/questions/37902946/add-item-to-the-collection-with-foreign-key-via-rest-call
标签: java spring spring-boot spring-data-jpa spring-data-rest