Spring JdbcTemplate / NamedParameterJdbcTemplate passing null value as a parameter value
Asked Answered
M

6

18

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.

Mcallister answered 15/2, 2012 at 2:1 Comment(2)
Are you set the dataSource for NamedParameterJDBCTemplate that returning from newNamedParameterJDBCTemplate()?Angus
xSNRG, can you share what was the problem? Answer by Titi is same as your code.Epimorphosis
B
17

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?

Bound answered 15/2, 2012 at 7:14 Comment(0)
I
13

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.

Icarian answered 15/2, 2012 at 4:10 Comment(0)
A
11

There is an extra space after parameter name:

params.addValue("project ", null);
                        ↑   
params.addValue("id ", 1);
                   ↑
Anathematize answered 19/6, 2017 at 21:16 Comment(0)
S
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);
Sande answered 4/10, 2019 at 15:21 Comment(1)
thanks, helped for me )Pirog
P
-1

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

Polyhedron answered 30/12, 2013 at 1:8 Comment(0)
E
-2

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";
Eurythmics answered 2/11, 2017 at 18:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.