Why does Spring's JDBC Templates doesn't use the tables default value

Viewed 4119

I have a table in MYSQL and I am using JDBC Templates to do an insert into that table.

One of the columns has a default value, and I am not specifying it in the Map<String, Object> parameters map.

I am getting an exception Column 'colName' cannot be null.

Can anyone explain this please?

Thanks

*Edit: code *

contactDetailsInsertTemplate = new SimpleJdbcInsert( dataSource ).withTableName("contactdetails").usingGeneratedKeyColumns("contactcode");
Map<String, Object> parameters = new HashMap<String, Object>();
Number newId = contactDetailsInsertTemplate.executeAndReturnKey(parameters);
5 Answers

You can add the columns which have a default value as parameters to usingGeneratedKeyColumns().
Column names included as parameters of that method will be omitted from the generated INSERT statement.

Since the OP is supplying a MAP to the SimpleJdbcInsert .

This is what I did.

  1. I made sure the MAP only has columns that I want inserted.

  2. I extracted the Map keys and converted them into String[] like below

     Set<String> set = map.keySet();
     String[] columnNames = (String[]) map.keySet().toArray(new String[set.size()]);`
    
  3. When initiating the SimpleJdbcInsert I passed in the columns I want to be used as below

     SimpleJdbcInsert sji = new SimpleJdbcInsert(dataSource).withTableName("table_name");
     sji.usingColumns(columnNames);`
    

Hope it helps.

Related