Spring JdbcTemplate / NamedParameterJdbcTemplate passing null value as a parameter value

41,122

Solution 1

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?

Solution 2

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.

Solution 3

There is an extra space after parameter name:

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

Solution 4

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);
Share:
41,122
AlexLiesenfeld
Author by

AlexLiesenfeld

Updated on July 17, 2022

Comments

  • AlexLiesenfeld
    AlexLiesenfeld almost 2 years

    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.

  • diana-pure
    diana-pure over 2 years
    thanks, helped for me )