1

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?

bijay limbu
  • 57
  • 2
  • 5

2 Answers2

1

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;
}
Nice Books
  • 1,675
  • 2
  • 17
  • 21
Andreas Radauer
  • 1,083
  • 7
  • 18
  • Thank You for the answer but it only saves person data whereas human data is null. I want to save on both entities with the only post of a person as both have the same column header and datatype – bijay limbu Sep 23 '21 at 11:30
0

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
   }
}
  • Thank You for the answer but what I am looking for is I want to post in both human and person with only { "human": {} }. I meant to say it should post on both with just human post. – bijay limbu Sep 23 '21 at 11:27
  • 1
    Can you update the question with your possible json body? maybe I can update my answer as well. – Rhadamez Gindri Hercilio Sep 23 '21 at 12:30