16

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.

AlexLiesenfeld
  • 2,872
  • 7
  • 36
  • 57

6 Answers6

16

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?

djm.im
  • 3,295
  • 4
  • 30
  • 45
12

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.

baba.kabira
  • 3,111
  • 2
  • 26
  • 37
9

There is an extra space after parameter name:

params.addValue("project ", null);
                        ↑   
params.addValue("id ", 1);
                   ↑
cnstntn
  • 91
  • 2
  • 3
2

Map.of() doesn't support null

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);
epox
  • 9,236
  • 1
  • 55
  • 38
-1

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

Kran
  • 69
  • 1
  • 3
-1

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";
Dalton Cézane
  • 3,672
  • 2
  • 35
  • 60