目前,我有一个使用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);
}
}一切似乎都正常工作。当我运行应用程序时,一切似乎都正常工作。我可以向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发布评论,我会得到一个不允许的HTTP405方法。
创建Comment资源并将其与此Post关联的正确方法是什么?如果可能的话,我想避免直接使用http://localhost:8080/comments的POSTing。
发布于 2014-10-17 22:09:45
你必须首先发表评论,在发表评论的同时,你可以创建一个关联帖子实体。
它应该看起来像下面这样:
http://{server:port}/comment METHOD:POST
{"author":"abc","content":"PQROHSFHFSHOFSHOSF", "post":"http://{server:port}/post/1"}而且它会工作得很好。
发布于 2017-06-28 03:03:19
有两种类型的映射关联和组合。在关联的情况下,我们使用了如下的连接表概念
员工--1到n->部门
因此,在关联Employee、Department、Employee_Department的情况下,将创建3个表
您只需要在代码中创建EmployeeRepository。除此之外,映射应该是这样的:
class EmployeeEntity{
@OnetoMany(CascadeType.ALL)
private List<Department> depts {
}
}部门实体现在将不包含任何用于外国key...so的映射,当您尝试在单个json请求中添加带有部门的员工的POST请求时,它将被添加...
发布于 2016-06-15 04:54:05
我遇到了同样的情况,我必须删除子实体的存储库类,因为我使用了一对多映射,并通过主实体本身提取数据。现在,我得到了包含数据的完整响应。
https://stackoverflow.com/questions/25311978
复制相似问题