Home > Mobile >  How to receive multiple RequestBody in a controller and save it according to its type in Spring Boot
How to receive multiple RequestBody in a controller and save it according to its type in Spring Boot

Time:09-25

I am new to spring boot, and Thank you in advance. I am facing a problem: I would like to receive two types of object in the controller, using the @ResponseBody, then save them.

I have two models

public class Person {
    int a;
    int b;
    int c;
}

public class Human {
    int a;
    int b;
    int c
}

By doing something like this:

@PostMapping(value="/save")
public void savePerson(@RequestBody Person person,  @RequestBody Human human) {
    personRepo.save(person);
    humanRepo.save(human);          
}

I want to save person and human on the same request. How to achieve this?

CodePudding user response:

Is Person and Human the same 'Entity'? I mean are the values from the post request the same?

If yes I would remove Human from the Arguments and create it based on Person

@PostMapping(value="/save")
public void savePerson(@RequestBody Person person) {
      
        Human human = mapPersonToHuman(); 
        personRepo.save(person);
        humanRepo.save(human);          
}

Otherwise if person and human are two different things, I would create a new Wrapper Object so you can a new messages with both entities.

public class PersonHumanWrapper{
    Person person;
    Human human;
}

CodePudding user response:

What you could do is: create an object with these two objects inside:

public class PersonAndHuman {

    private Person person;
    private Human human;

    // getters and setters...
}

And your controller should receive this object:

@PostMapping(value="/save")
public void savePerson(@RequestBody PersonAndHuman personAndHuman) {
    personRepo.save(personAndHuman.getPerson());
    humanRepo.save(personAndHuman.getHuman());          
}

Now, if you are using JSON to make the post, do something like:

{
   "human" : {
       //body here
   },
   "person": {
       //body here
   }
}
  • Related