2

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.

1 Answer 1

2

You can use URL to specify a notebook you want to add a word to (RESTful approach):

@RequestMapping(value = "/notebooks/{name}/words", method = RequestMethod.POST, headers = {"Content-type=application/json"})
@ResponseBody
public void addWord(
    @PathVariable("name") String notebookName, 
    @RequestBody Word word, 
    HttpSession session) { ... }

Alternatively, if you prefer more RPC-style approach, you can add notebook name to your command object:

@RequestMapping(value = "/doAddWord", method = RequestMethod.POST, headers = {"Content-type=application/json"})
@ResponseBody
public void addWord(@RequestBody AddWordCommand command, HttpSession session) { ... }

.

public class AddWordCommand {
    private String notebookName;
    private Word word;
    ...
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.