Reputation: 19
I have a basic diary project and a one to many relationship with two entities, User and DiaryEntry. The problem is I have two ways to add data, one being bi-directional and the other uni. The trouble with the bi-directional approach is that I can not get the id off the diary object recently added to the database to send to the user but I am not sure how important this actually is. The other approach is to use a uni directional which allows me to get the diary object added directly and return it to the user but most advice online is to use bi-directional approaches. Any advice appreciated as I am just trying to get familiar with the best approaches to spring rest apps.
public void createDiaryEntryNoResult(Long uId, DiaryEntryDTO diaryEntryDTO) {
userRepository.findById(uId)
.map(user -> {
DiaryEntry diaryEntry =
diaryEntryMapper.diaryEntryDTOToDiaryEntry(diaryEntryDTO);
user.addDiaryEntry(diaryEntry);
userRepository.save(user);
return user;
})
.orElseThrow(ResourceNotFoundException::new);
}
public DiaryEntryDTO createDiaryEntryWithResult(Long uId, DiaryEntryDTO diaryEntryDTO) {
DiaryEntry diaryEntry = diaryEntryMapper.diaryEntryDTOToDiaryEntry(diaryEntryDTO);
User user = userRepository.findById(uId).orElseThrow(ResourceNotFoundException::new);
diaryEntry.setUser(user);
DiaryEntry savedDiaryEntry = diaryEntryRepository.save(diaryEntry);
return diaryEntryMapper.diaryEntryToDiaryEntryDTO(savedDiaryEntry);
}
Upvotes: 1
Views: 722
Reputation: 1004
"The trouble with the bi-directional approach is that I can not get the id off the diary object recently added to the database to send to the user but I am not sure how important this actually is."
The id should be present in savedDiaryEntry after calling save method...
There is no "correct" approach - it depends on the person using the API.
Do they need the id in the response at that moment or is it for information purpose only? If for some reason you need that id to call some other API methods then correct approach would be of course to return the id in the response otherwise it's ok to return no content.
If they don't need the id at the moment then returning only "200 OK" or "201 No content" response with no body is correct approach, it all depends on what the person calling the API will need at the time or what's more convenient for them...
Upvotes: 1