Issue
Something very bizarre have been happening. I have a very simple Entity recipe like so
@Data
@Entity
@Table(name = "recipe", schema = "public")
@AllArgsConstructor
@NoArgsConstructor
public class Recipe {
@Id
@GeneratedValue(
strategy = GenerationType.IDENTITY
)
@Column(name = "id", updatable = false, nullable = false)
private long id;
@Column(name = "name")
private String name;
@Column(name = "instructions")
private String instructions;
@Column(name = "date_added", nullable = false)
private String dateAdded;
@Column(name = "last_edited", nullable = false)
private String lastEdited;
}
and I have this post service that should post the 4 string attribute to the database
public void postRecipe(Recipe recipe){
var sql = """
INSERT INTO public.recipe ("name","instructions","date_added","last_edited")
VALUES (?, ?, ?, ?)
""";
jdbcTemplate.update(
sql,
recipe.getName(),
recipe.getInstructions(),
recipe.getDateAdded(),
recipe.getLastEdited()
);
}
However when the following jason is sent using postman, I get the null value error.
{
"name":"test",
"instructions":"don't eat",
"date_added":"03/04/2017",
"last_edited":"03/04/2017"
}
ERROR: null value in column \"date_added\" of relation \"recipe\" violates not-null constraint\n Detail: Failing row contains (3, null, don't eat, null, test)
The strangest thing is that only the "name" and "instruction" columns receive their data and not the other columns. I have tried adding another String attribute to the Entity class and it also cannot get data from the jason.
Edit 1: I have tried adding the data directly through pgadmin and it worked fine
INSERT INTO recipe (name, instructions, date_added, last_edited)
VALUES ('test', 'test instruction', '2020/03/05', '2020/05/08');
Solution
It looks like your deserialization is broken - transforming your JSON into the Java entity, which results in some null values present. Most likely because date_added
!= dateAdded
(field name), and Jackson cannot properly set a value.
I recommend having a look at Jackson guide: https://www.baeldung.com/jackson-annotations, @JsonProperty
specifically. And overall do not mix entities and DTOs
Answered By - vladtkachuk
Answer Checked By - Willingham (JavaFixing Volunteer)