Erick Cruz
Erick Cruz

Reputation: 11

Rest service in SpringBoot expects a nested object in JSON from GET request

I am using SpringBoot. I have two entities, Users and Role. For each user record I want to assign a role.

In my entities I already have the relationship and the database is built as I want.

When I see the service, it asks me for the Role object when I want to save the user. Am I right in wanting to create the User record? Or with @AutoWired can I add in my repository class the instance of Role and search it by id?

What do you recommend? I am still newbie with Rest services.

As an example, when invoking the create user service, the JSON it expects is the following:

{ 
  "id": 1,
  "usuario": "JUANITO",
  "password": "*********",
  "correo": "[email protected]",
  "estado": "ACTIVO",
  "fecha": 12125368254,
  "rol": {
    "descripcion": "ADMIN",
    "estado": "ACTIVO",
    "id": 1
  }
}

I wish it was something similar to this:

{
  "id": 1,
  "usuario": "JUANITO",
  "password": "*********",
  "correo": "[email protected]",
  "estado": "ACTIVO",
  "fecha": 12125368254,
  "rol": 1
}

That is, I do NOT want to create a new Role object, but use an existing one and assign it to my User record.

Upvotes: 1

Views: 541

Answers (1)

João Dias
João Dias

Reputation: 17510

Or with @AutoWired can I add in my repository class the instance of Role and search it by id?

No, you can't simply autowire the instance of the given Role at runtime dynamically. If you want to be able to use the 2nd JSON you need to get the Role entity associated with the given ID, then set it in your User object and only then you can use your repository to save the User.

Upvotes: 0

Related Questions