SimpleJdbcInsert未自动填充SQL表默认约束值问题求助
问题分析与解决
问题描述
创建的Employee表中,empOrgId列已设置默认值13,但使用SimpleJdbcInsert插入数据时,未传入该字段却报错提示无法插入NULL值:
com.microsoft.sqlserver.jdbc.SQLServerException: 无法将值 NULL 插入列 'empOrgId',表 'Employee';列不允许有空值。INSERT 失败。
表创建脚本
CREATE TABLE [dbo].[Employee]( [empId] [int] IDENTITY(9,1) NOT NULL, [empName] VARCHAR(255) NOT NULL, [empOrgId] [int] NOT NULL, ) ALTER TABLE [dbo].[Employee] ADD CONSTRAINT [DF__Employee__empOrgId] DEFAULT ((13)) FOR [empOrgId] GO
插入代码
SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate); simpleJdbcInsert.withTableName("Employee") .usingGeneratedKeyColumns("empId"); SqlParameterSource params = new MapSqlParameterSource() .addValue("empName","john"); Number number = simpleJdbcInsert.executeAndReturnKey(params); System.out.println("number"+number);
原因
SimpleJdbcInsert默认会读取表的元数据,生成包含所有非空且非自增列的INSERT语句。当未传入empOrgId时,它会在INSERT语句中为该列赋值NULL,而非省略该列让数据库自动应用默认值。
解决方案
方案1:显式指定要插入的列(推荐)
通过usingColumns()方法明确指定需要插入的字段,生成的INSERT语句只会包含这些字段,未指定的empOrgId将由数据库自动使用默认值:
SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(jdbcTemplate); simpleJdbcInsert.withTableName("Employee") .usingGeneratedKeyColumns("empId") .usingColumns("empName"); // 仅指定要插入的列 SqlParameterSource params = new MapSqlParameterSource() .addValue("empName","john"); Number number = simpleJdbcInsert.executeAndReturnKey(params); System.out.println("number"+number);
方案2:手动传入默认值
直接在参数中添加empOrgId的默认值,但此方式会将默认值硬编码到代码中,后续数据库默认值修改时需同步更新代码:
SqlParameterSource params = new MapSqlParameterSource() .addValue("empName","john") .addValue("empOrgId", 13); // 手动传入默认值
内容的提问来源于stack exchange,提问作者java_tech
相关产品推荐
相关产品推荐

