Currently I have a Spring Boot application using Spring Data REST. I have a domain entity Post
which has the @OneToMany
relationship to another domain entity, 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;
// 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...
}
Their Spring Data REST JPA repositories are basic 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 configured 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 appears to work correctly. When I run the application, everything appears to work correctly. I can POST a new Post object to http://localhost:8080/posts
like so:
Body:
{"author":"testAuthor", "title":"test", "content":"hello world"}
Result at 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 perform a GET at http://localhost:8080/posts/1/comments
I get an empty object {}
returned, and if I try to POST a comment to the same URI, I get an HTTP 405 Method Not Allowed.
What is the correct way to create a Comment
resource and associate it with this Post
? I'd like to avoid POSTing directly to http://localhost:8080/comments
if possible.