Home > other >  How to save multiple multiple model data at the same time in spring boot?
How to save multiple multiple model data at the same time in spring boot?

Time:09-23

Hy, I am new to spring boot, and Thankyou in advance. I am facing a problem

I have two models

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



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

while saving this model in the controller

@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