Home > database >  java spring boot Entity constructor with arguments does not execute
java spring boot Entity constructor with arguments does not execute

Time:02-27

i do not understand why an Entity no argument constructor is being called when providing a request body? if i delete it and the only constructor that exist is the one that receive arguments, i get the expected output print, but i must implement a no argument constructor in order to save the Entity in the database. this is the request body:

{
"str": "stringgg",
"intt": 2,
"doublee": 1.003
}

this is the route: when commenting out the empty constructor, the values of the new instance match the request json body

@PostMapping("/save")
public List<Modell> obj(@RequestBody Modell model) {
    modelRepository.save(model);
    System.out.println(model.toString());
    return modelRepository.findAll();
}

this is the entity class:

@Table(name = "modelltbl")
@Entity
public class Modell {
    
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id", nullable = false)
    private long id;

    @Column(name = "str", nullable = true)
    private String str;

    @Column(name = "intt", nullable = true)
    private int intt;

    @Column(name = "doublee", nullable = true)
    private double doublee;

    public Modell(String str, int intt, double doublee)
    {
        this.str = str;
        this.intt = intt;
        this.doublee = doublee;
    }
    public Modell(){}


    @Override
    public String toString()
    {
        return String.format("model class,params: %s , %o , %f ", str , intt, doublee);
    }
}

CodePudding user response:

First of all: Do not use entities iat controller level. It is bad application Design.

The json will be converted throug jackson library which creates the object by calling the default constructor and the setter of the properties. If you do not want this behavior you can use the @JsonCreator annotation.

@JsonCreator
public Modell(@JsonProperty("str")String str, @JsonProperty("intt")int intt, @JsonProperty("doublee")double doublee)
{
    this.str = str;
    this.intt = intt;
    this.doublee = doublee;
}
  • Related