Reputation:
I have an issue passing a null value to NamedParameterJdbcTemplate using MapSqlParameterSource of the spring framework. Anyone knows how to do this?
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.
Upvotes: 18
Views: 50690
Reputation: 10900
ISSUE: Map.of doesn't support null values, but HashMap does:
String sql = "update person set project = :project where id = :id;";
Map<String, Object> params = new HashMap<>(2);
params.put("project", null);
params.put("id", 1);
int count = newNamedParameterJDBCTemplate().update(sql, params);
Upvotes: 3
Reputation: 888
This is my code on 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?
Upvotes: 17
Reputation: 9
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:
String sql = "update person set project = :project where id = :id";
Upvotes: -2
Reputation: 111
There is an extra space after parameter name:
params.addValue("project ", null);
↑
params.addValue("id ", 1);
↑
Upvotes: 11
Reputation: 79
Please make sure if datasource is set for your jdbcTemplate like below as an example namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
Upvotes: -1
Reputation: 3171
In pure jdbc its PreparedStatement.setNull(int,java.sql.Types.NULL);
From MapSqlParameterSource api there is
addValue(String paramName, Object value,int sqlType)
try providing java.sql.Types.NULL as sqlType.
May be this helps.
Upvotes: 13