我在 MYSQL 中有一个表,我正在使用 JDBC 模板向该表中插入数据。
其中一列有默认值,我没有在 Map<String, Object> parameters
中指定它 map 。
我遇到异常 Column 'colName' cannot be null
.
有人能解释一下吗?
谢谢
*编辑:代码*
contactDetailsInsertTemplate = new SimpleJdbcInsert( dataSource ).withTableName("contactdetails").usingGeneratedKeyColumns("contactcode"); Map<String, Object> parameters = new HashMap<String, Object>(); Number newId = contactDetailsInsertTemplate.executeAndReturnKey(parameters);
最佳答案
您需要限制在 SQL Insert 中指定的列。
参见 SimpleJdbcInsert.usingColumns()
如果不这样做,SQL 语句将需要所有列的值,并且不能使用默认值。
例如使用
insert into mytable (col1, col2) values (val1, val2);
代替
insert into mytable values (val1, val2);
关于java - 为什么 Spring 的 JDBC 模板不使用表的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20497985/