user911651
user911651

Reputation:

Spring JdbcTemplate / NamedParameterJdbcTemplate passing null value as a parameter value

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

Answers (6)

epox
epox

Reputation: 10900

Map.of() doesn't support null

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

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

Tanya verma
Tanya verma

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

cnstntn
cnstntn

Reputation: 111

There is an extra space after parameter name:

params.addValue("project ", null);
                        ↑   
params.addValue("id ", 1);
                   ↑

Upvotes: 11

Knp
Knp

Reputation: 79

Please make sure if datasource is set for your jdbcTemplate like below as an example namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

Upvotes: -1

baba.kabira
baba.kabira

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

Related Questions