Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring - JPA - insert - not passing value for field that has default throws error

Some of the non-nullable fields in table have default value. When inserting new rows into table via JPA, I do not want to pass any value for these fields so that they get the default values. However, when inserting new row via Spring JPA repository classes, I get an error that null values cannot be inserted. I noticed that the insert statement JPA sends to the database have all fields listed:

insert into table (field1, field2, field3) values ('abc',null,null);

Since field2 and field3 have null specified, the default values are not assigned and database throws error that null values cannot be inserted. Is there a workaround?

like image 955
dsatish Avatar asked Feb 20 '23 03:02

dsatish


2 Answers

You can try to configure insertable property for @Column, which shouldn't be persisted & to exclude it from the insert statement.

From Documentation - insertable : (Optional) Whether the column is included in SQL INSERT statements generated by the persistence provider.

like image 80
Nayan Wadekar Avatar answered Apr 27 '23 17:04

Nayan Wadekar


If you want to assign default value to database. you shouldn't insert it as NULL rather you have to leave it out, and don't insert it, to do that you can use, @Column(insertable = false) annotation.

As the matter of fact I think it's not good job to assign default value in database when you work to gather with ORM. choose an other way such as JPA Events to initiate all values in JAVA.

like image 26
Iman Avatar answered Apr 27 '23 17:04

Iman