Spring JdbcTemplate / NamedParameterJdbcTemplate 传递空值作为参数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9286942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring JdbcTemplate / NamedParameterJdbcTemplate passing null value as a parameter value
提问by AlexLiesenfeld
I have an issue passing a null value to NamedParameterJdbcTemplate using MapSqlParameterSource of the spring framework. Anyone knows how to do this?
我有一个问题,使用 spring 框架的 MapSqlParameterSource 将空值传递给 NamedParameterJdbcTemplate。任何人都知道如何做到这一点?
Currently my code is :
目前我的代码是:
String sql = "update person set project = :project where id = :id;";
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("project ", null);
params.addValue("id ", 1);
int count = newNamedParameterJDBCTemplate().update(sql, params);
This is where I get a NullPointerException.
这是我得到 NullPointerException 的地方。
回答by Titi Wangsa Bin Damhore
This is my code on Spring 3.1
这是我在 Spring 3.1 上的代码
String sql = "update user set name = :name where id = :id";
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("name", null);
params.addValue("id", 1);
namedParameterJdbcTemplate.update(sql, params);
works fine. Maybe a stack trace might help?
工作正常。也许堆栈跟踪可能会有所帮助?
回答by baba.kabira
In pure jdbc its PreparedStatement.setNull(int,java.sql.Types.NULL);
From MapSqlParameterSource api there is
在纯 jdbc 中它的 PreparedStatement.setNull(int,java.sql.Types.NULL);
从 MapSqlParameterSource api 有
addValue(String paramName, Object value,int sqlType)
try providing java.sql.Types.NULL as sqlType.
尝试提供 java.sql.Types.NULL 作为 sqlType。
May be this helps.
可能这有帮助。
回答by cnstntn
There is an extra space after parameter name:
参数名后有一个额外的空格:
params.addValue("project ", null);
↑
params.addValue("id ", 1);
↑
回答by epox
String sql = "update person set project = :project where id = :id;";
// ISSUE: Map.of doesn't support null values, but HashMap does:
Map<String, Object> params = new HashMap<>();
params.put("project", null);
params.put("id", 1);
int count = newNamedParameterJDBCTemplate().update(sql, params);
回答by Tanya verma
I think semicolon is extra in code below:
我认为分号在下面的代码中是额外的:
String sql = "update person set project = :project where id = :id;";
Remove semicolon after id. It should be like:
删除 id 后的分号。它应该是这样的:
String sql = "update person set project = :project where id = :id";
回答by Kran
Please make sure if datasource is set for your jdbcTemplate like below as an example namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
请确保是否为您的 jdbcTemplate 设置了数据源,例如如下所示 namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

