Zum Hauptinhalt springen

Error Handling

RuntimeException -> HTTPSTATUS

Why do I get Cannot map null into type int when creating a new object? (Spring Boot)

I sent a POST request with JSON but didn't include an ID, because the database generates the ID automatically.

My Entity class had int id (a primitive type) and a constructor which expects this id:

public class Ingredient {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String ingredientName;

public Ingredient (){}

public Ingredient(int id, String ingredientName){
this.id = id; <<<<<<<<<--------- The id is expected when instantiating an "Ingredient" object
this.ingredientName = ingredientName;
}
}

Although the model class also has an empty constructor (needed to create a bean in memory), Jackson (the library responsible for taking the JSON and instantiating the object using the constructor) uses the manual (second) constructor. As the JSON sent in the POST request had no id (which is correct, because it is generated on the fly by the DB) it tried to pass null into the constructor. As the type int can't by default ever be null Spring throws the error "Cannot map null into type int".

To avoid this we can just omit the id in the constructor. It makes sense, as it's not needed anyway for instantiating objects (even manually). SO the class should look like this:

public class Ingredient {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String ingredientName;

public Ingredient (){}

public Ingredient(String ingredientName){
*********NO ID HERE*********
this.ingredientName = ingredientName;
}
}

Generally, we could use the Integer type (object) instead of int (primitive) as it allows null as a value. When the method save() in the Repository is called, Hibernate will see the object with id=null (or 0 if it forces a default) which means it is a new item and will send the SQL to create a new record (and the id will be created by the DB itself).