Question

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);
Was it helpful?

Solution

You need to limit the columns specified in the SQL Insert.

See SimpleJdbcInsert.usingColumns()

If you don't do this, the SQL statement will need values for ALL columns and the default values cannot be used.

e.g. use

insert into mytable (col1, col2) values (val1, val2);

instead of

insert into mytable values (val1, val2);

OTHER TIPS

The problem is somewhere else: when I use SimpleJdbcInsert and pass a map of parameters to it, I simple expect to create insert statment only with parameters I provided. I have a NOT NULL column in the table with DEFAULT value and I don't want to specify it. I also don't want to explicitly put all column names in usingColumns() as I've just do it when creating a map of parameters! Why should I do it again? The problem is that SimpleJdbcInsert want's to be smarter and add all columns to insert statement which is not necessary. Why not create a statement only using columns provided with parameters map?

See: http://forum.spring.io/forum/spring-projects/data/54209-simplejdbcinsert-and-columns-with-default-values

INSERT INTO mytable (1,null) is not the same as INSERT INTO mytable (1). The prior specifically inserts null, the later leaves the decision up to the DB (which would be the default value). Spring JDBC is doing the former.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top