2

CrudRepository#save doesn't allow you to use default columns. null-fields of an entity are interpreted as NULL not DEFAULT.

If I use a custom @Query("INSERT INTO ... DEFAULT ..."), then I'm unable to obtain the ID of the inserted row.

Tobi Akinyemi
  • 804
  • 1
  • 8
  • 24
  • Can you not set the default values on the Bean itself? – Jay Oct 19 '20 at 14:57
  • A bit more code would be appreciated by many I think. – Joop Eggen Oct 19 '20 at 14:58
  • 1
    @Jay Here's what I said to JenSchauder: `my reason for not using save is it doesn't seem to support default columns values. Perhaps I could specify the column default in a column definition (like you can with JPA) but this isn't ideal, as now the column definition is duplicated - in the code and in the actual database schema; i.e. if I change the DB schema I must remember to change the code column definition`. Your answer does what I'm trying to avoid – Tobi Akinyemi Oct 19 '20 at 15:16

1 Answers1

0

There is currently no build in way of using the default values from the database.

While @Jay's answer isn't aimed at Spring Data JDBC, the approach of setting the attributes to their default value in the constructor does work with Spring Data JDBC.

The alternative would be to implement a custom method which does the insert and retrieves the default values back from the database.

AFAIK not all databases support more then one return value from an insert so you might have to actually reselect the data written to the database.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • I'm only trying to retrieve the ID; i.e.: `INSERT INTO table (id, field, field_with_default, ...) VALUES (DEFAULT, :value, DEFAULT, ...)`, obtaining the generated `id`. (in reality this query would be abbreviated to `INSERT INTO table (field, ...) VALUES (:value, ...)`) – Tobi Akinyemi Oct 20 '20 at 10:07
  • I think [DATAJDBC-618](https://jira.spring.io/browse/DATAJDBC-618) would be a good addition (functionality already supported in spring data jpa), which would solve this issue. – Tobi Akinyemi Oct 20 '20 at 10:11