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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With