1

I found a similar problem here and tried to fix it, but it still does not work.

Using: Hibernate, Spring MVC

I have a @ManyToMany relationship between the entities Traveler and Address.

If I create the Traveler and Address individually by their own controller, it works. But if I try to create a Traveler and the appropriate Address by the following controller, I get a 400 Bad request error:

    @RequestMapping(value = "/travelers", method=RequestMethod.POST)
    public @ResponseBody Traveler createTraveler(@RequestBody Traveler traveler, Address address) {
    logger.info("Start createTraveler");
    System.out.println("Received traveler: " + traveler.getLastName());
    travelerDAO.save(traveler);
    System.out.println("Received address: " + address.getStreet());
    addressDAO.save(address);
    logger.info("End createTraveler");
    return traveler;
}
2
  • 1
    There is only a single body, so you would only have a Traveler and with proper JPA configuration that would also store the Address. No need for 2 calls of 2 objects in your method signature.
    – M. Deinum
    Sep 8, 2015 at 8:16
  • Thanks. Your hint helped me to solve the problem!
    – Marcel
    Sep 8, 2015 at 10:40

1 Answer 1

1

If your JSON payload is traveler object with nested addresses, spring should fill in collection of addresses for Traveler automatically (with help of Jackson). Try it without address parameter.

@RequestMapping(value = "/travelers", method=RequestMethod.POST)
    public @ResponseBody Traveler createTraveler(@RequestBody Traveler traveler) {

   logger.info("Start createTraveler");
    System.out.println("Received traveler: " + traveler.getLastName());
    travelerDAO.save(traveler);
    System.out.println("Received addresses: " + traveler.getAddresses());
    //save addresses in loop
    return traveler;

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.