I am developing a simple dictionary RESTful API with Spring-mvc. There are two related entities:
public class Word {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String word;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="LANGUAGE_ID", insertable=false, updatable=false)
private Language language;
}
Based on the code above the related entity is Language
.
Issue: I would like to implement the CREATE operation on the Word entity with POST request. The implementation is not difficult, but I did find at least two solution candidates in relation to the POST request URL and JSON request body:
Solution Candicate I: directly insert with JSON body request. The JSON body contain the nested JSON object - Language, something like
{id:1, word:"hello", Language: {id:1, language:"English"}}
reference: Spring: Save object with foreign keys with a POST request
Solution Candidate II: get the referenced Language id through the POST request URL, say something like
POST http://localhost:8080/rest/language/1/words
As such, there is no Language
reference at all in the JSON POST request body.
reference: https://www.youtube.com/watch?v=_Jnu_jHfQbM
I have 2 questions:
Question 1: among these two solution candidates, which is the better one, or say professional standard solution? or is there any other solution?
Question 2: as to both the given solution candidate, in any case we need to retrieve the referenced Language
POJO at least in the corresponding controller
class. But from the perspective of OO-design principle, this way seems to be tightly coupled with the controller, so I am thinking that should we decouple this retrieval behavior somewhere else than in controller? for instance in the service
layer. But is this the professional way? and we need to have a corresponding DTO?