T
T
TonyJa2018-07-01 09:37:39
Java
TonyJa, 2018-07-01 09:37:39

Is it possible to accept a parent entity in a Rest controller?

Good day.
Tell me, is it possible to accept the entity of the parent (abstract class) in the REST controller?
For example:
Abstract class:

public abstract class Warrior {
    long id;
    String name;
    Integer age;
    Type type;

the Type class is an enum and there are 2 values ​​Attackers and Defenders
Then there are 2 successor classes Warrior -> Attackers and Defenders
Attackers
public class Attackers extends Warrior {
  int power;
  boolean magic;
}

Defenders
public class Defenders extends Warrior {
    int def;
    int magicDef;
}

Essence of a question: whether I can accept Warrior in the controler?
Like this:
@PostMapping(value = "/create")
 public ResponseEntity<Long> createWarrior(@RequestParam Warrior warrior){
        return ResponseEntity.ok(service.createWarrior(warrior));
    }

But in fact, there will be inherited entities, according to the Type field, in the factory, I will determine which entity to cast to the entity I need and save to the database.
I have now done so, but the 400 response always comes.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
TonyJa, 2018-07-02
@TonyJa

I solved the problem by changing @RequestParam to @RequestBody.

K
Kirill Romanov, 2018-07-01
@Djaler

https://stackoverflow.com/a/30386694 something like this

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question