I currently have a Spring boot application using Spring Data REST. I have a Post domain object that has @OneToMany related to another domain object, Comment . These classes are structured as follows:
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;
Comment.java:
@Entity public class Comment { @Id @GeneratedValue private long id; private String author; private String content; @ManyToOne private Post post;
Their Spring Data REST JPA repositories are the base implementations of CrudRepository :
PostRepository.java:
public interface PostRepository extends CrudRepository<Post, Long> { }
CommentRepository.java:
public interface CommentRepository extends CrudRepository<Comment, Long> { }
The application entry point is a standard, simple Spring boot application. Everything is set up for stock.
Application.java
@Configuration @EnableJpaRepositories @Import(RepositoryRestMvcConfiguration.class) @EnableAutoConfiguration public class Application { public static void main(final String[] args) { SpringApplication.run(Application.class, args); } }
Everything is working correctly. When I run the application, everything works correctly. I can send POST a new Post object to http://localhost:8080/posts as follows:
Body: {"author":"testAuthor", "title":"test", "content":"hello world"}
Result 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" } } }
However, when I do a GET at http://localhost:8080/posts/1/comments , I return an empty {} object, and if I try to send a POST message to the same URI, I get an HTTP 405 method that is not allowed.
What is the correct way to create a Comment resource and associate it with this Post ? I would like to avoid POSTing directly http://localhost:8080/comments , if possible.