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;
}
luboskrnac
  • 23,973
  • 10
  • 81
  • 92
Marcel
  • 1,537
  • 5
  • 19
  • 38
  • 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 08 '15 at 08:16
  • Thanks. Your hint helped me to solve the problem! – Marcel Sep 08 '15 at 10:40

1 Answers1

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;
luboskrnac
  • 23,973
  • 10
  • 81
  • 92