I have two entities: Word and Notebook. I'm trying to save word to the database using jQuery ajax method.Spring MVC can be setup to automatically bind incoming JSON string into a Java object and it works great. But there is a question associated with foreign key. What if my Word entity depends on Notebook entity.
Here is how i sent request to Controller
$.ajax({
type: "POST",
url: "/doAddWord",
data: JSON.stringify({ word: word, translation: translation, transcription: transcription, example: examples }),
contentType: 'application/json',
success: function() {
alert('success');
}
});
Here is method in controller:
@RequestMapping(value = "/doAddWord", method = RequestMethod.POST, headers = {"Content-type=application/json"})
@ResponseBody
public void addWord(@RequestBody Word word, HttpSession session) {
Integer userId = (Integer)session.getAttribute("userId");
Notebook notebook = notebookService.findByName("default", userId);
word.setNotebook(notebook);
wordService.add(word);
}
So as you can see in my Controller i get notebook from data base by notebook name (now it is hardcoded "default") and by user id. In my jquery code i should send notebook name. I can not just add notebook name to my json cause i'm getting 500 Erorr and cause it's not just String it is Object.
Is there any way how to send to controller multi data: json and some value or may be some other tips how i can implement it.
Thanks in advance.