Home > OS >  Can you set a controller for multiple models in Spring boot?
Can you set a controller for multiple models in Spring boot?

Time:12-15

So I'm trying to add comments to 3 different models (Comments for movies, directors, and actors all foreign keyed to their id) but it feels like it would be very inefficient to create a model, controller, service, and repository for each one of them and that it would be easiest to just create a new comment model for each and put them all into a single controller and work on it from there. Is that possible? Or is there an even more efficient way to do this through a single model? It doesn't seem like it is possible as they are set up as a many-to-one relationship. I just want to be sure that it isn't bad practice or anything like that to do, I'd just rather not have so much extra code that feels repeated. Can anyone give some advice on this? Thanks!

CodePudding user response:

Perhaps combining the POSTing of comments into a single endpoint may be achieved as such:

@PostMapping("/{targetType}/{targetTypeId}/comments")

Where targetType may be either 'movies', 'directors' or 'actors' and targetTypeId refers to the exact instance the comment should be linked to.

In the comment DB table, there will need to be a column TYPE_ID indicating which of the three target types the comment refers to and a column TYPE_INSTANCE_ID pointing to either a movie, director or actor.

| COMMENT table columns |
| ID | TYPE_ID | TYPE_INSTANCE_ID | COMMENT |
  • Related