0

I have two models:

// users.java
@Document(collection="user")
public class User {
    
    @MongoId(FieldType.STRING)
    private String id;
    private String firstname;
    // ....
}
// cars.java
@Document(collection="cars")
public class Cars {
    
    @MongoId(FieldType.STRING)
    private String id;
    private String owner;
    private String type;
    private String year;
}

How to collect the data with Spring Rest in controllers like:

@PostMapping("add")
public String save (@RequestBody User user,@RequestBody Cars cars){
    String theUser =  user.getFirstname;
    String theCars = cars.getType;
}

I need to save JSON like below:

{
    "firstname": "Smith",
    "type": "kfc",
    // more data blabla ......
}

Please tell me if you need more data like my pom.xml or other.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
dhanyn10
  • 704
  • 1
  • 9
  • 26
  • You want to mix the data of users and cars in a json? Why? I'd rethink that design and maybe create something like `{"user": {"firstname": ...}, "car" : {"type": ...}}`. – Thomas Jan 17 '23 at 15:42
  • @XtremeBaumer your answer is different, they're using string, not model. – dhanyn10 Jan 17 '23 at 15:45
  • @Thomas so my condition is impossible? – dhanyn10 Jan 17 '23 at 15:45
  • 1
    `@RequestBody annotated parameter is expected to hold the entire body of the request and bind to one object` if you would actually read the answers... – XtremeBaumer Jan 17 '23 at 15:46
  • 1
    Your condition doesn't make sense and looks like bad design. If you really need to do it that way, can you elaborate why? – Thomas Jan 17 '23 at 15:48
  • @Thomas im new in spring and this time have to do some test case. Currently i dont have any better option. – dhanyn10 Jan 17 '23 at 15:50
  • Yes, you can, your json will look like this: ```` { "user": { "id": "3", "firstname": "John", [...] }, "cars": { "id": "5", "owner": ... "type": ... [...] } } ```` – Octavia Jan 17 '23 at 15:53
  • 1
    But I would suggest you to make a DTO with only those two fields that you need. – Octavia Jan 17 '23 at 15:54
  • This is not an issue with spring but a general one. You should not mix data of 2 objects into one unless you really need to. Of course you could create a class like `UserCar` that contains everything but that looks like bad design too. Just think about what would happen if both users and cars would have a property "age" - in the combined class whose age would it be? – Thomas Jan 17 '23 at 15:54
  • Okay thank you for all. I will try another way. – dhanyn10 Jan 17 '23 at 16:02

0 Answers0