0
votes

I have a Spring Boot application working with Spring Data Rest. I have a domain entity Post which has a @OneToMany relationship to a domain entity Comment. For both entities I created a Repository interface.

So far, I have one controller called PostController which handles both entites. Via http://localhost:8080/posts/1/ I get the post with Id 1. In addition, via http://localhost:8080/posts/1/comments I get all comments on the post with Id 1.

I wonder whether this is the right approach with a single controller for both entites or if I should write a single controller for each of the Post and Comments entities?

2
if you use spring data rest, this will be automatically created for you. Have you tried that? - Randika Hapugoda
Why are you using your own controllers with Spring Data Rest? You know that SDR creates "controllers" for you automatically right? - Neil McGuigan

2 Answers

0
votes

In a similar project, my boss told me to use only a single Repository interface for both entities related like this. I will use only the Post entity-related Repository, not the Comments one, and then use the mapping to populate the Comments entity indirectly.

About the controller, I think it's okay, but I could be wrong.

0
votes

Using two repositories is the right approach since your database has the two entities stored in different tables. Perhaps some time in the future you'll need to search for comments and the second repository will help with this.

Regarding REST, your url looks good. So, if you don't need a new endpoint then a single controller sounds ok to me.

I would add a second controller if I had an endpoint that looked like this :

http://localhost:8080/comments