无法在Spring引导数据中直接发布到子资源

时间:2016-09-09 22:01:56

标签: java spring spring-boot spring-rest

我有一个基本的spring boot数据rest api,帖子里面有很多评论。我的问题是,我似乎无法找到一种方法将我的评论直接发布到子资源uri,如http://localhost:8090/posts/1/comments

我能够做到的唯一方法是首先在http://localhost:8090/comments创建评论资源,然后将评论uri发布到http://localhost:8090/posts/1/comments

这似乎是一个非常糟糕的主意,因为评论永远不能单独存在,只能链接到帖子。

是否有人知道如何将此作为一个操作,否则我将不得不手动处理评论发布的潜在孤立评论,但不会因任何原因发布到http://localhost:8090/posts/1/comments

我的代码如下。 任何帮助都会受到大力赞赏。

@Entity
public class Comment extends ResourceSupport {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonIgnore
private Long id;

private String comment;

@ManyToOne
private Post post;

@ManyToOne
private User sender;

protected Comment() {};

public void setId(Long id) {
    this.id = id;
}

public String getComment() {
    return comment;
}

public void setComment(String comment) {
    this.comment = comment;
}

public User getSender() {
    return sender;
}

public void setSender(User sender) {
    this.sender = sender;
}

public Post getPost() {
    return post;
}

public void setPost(Post post) {
    this.post = post;
}


@Entity
public class Post extends ResourceSupport {

@Id
@GeneratedValue(strategy= GenerationType.AUTO)
private @JsonIgnore Long id;

private String text;

@OneToMany
private List<Comment> comments;

protected Post () {};

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}

public List<Comment> getComments() {
    return comments;
}

public void setComments(List<Comment> comments) {
    this.comments = comments;
}
}

@RepositoryRestResource
public interface PostRepository extends PagingAndSortingRepository<Post, Long> {}

@RepositoryRestResource
public interface CommentRepository extends PagingAndSortingRepository<Comment, Long> {}


@SpringBootApplication
@EnableJpaRepositories("rest.api.repository")
@EnableWebMvc
@EnableTransactionManagement
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer{

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);

}

json我试图将评论发布到帖子中

{
   "comment": "some text",
   "sender": "http://localhost:8090/users/1"
}

1 个答案:

答案 0 :(得分:0)

原来我需要在我的Post类的评论列表中使用映射,即@OneToMany(mappedBy =“post”)。 现在我可以发布到http://localhost:8090/comments,然后当我按照之前的http://localhost:8090/posts/1/comments链接时,我现在看到评论。