Andrunevchyn

Andrunevchyn


December 2017
M T W T F S S
 123
45678910
11121314151617
18192021222324
25262728293031

Categories


AssertionError on jdbc request

Andriy AndrunevchynAndriy Andrunevchyn

If you got such error on jdbc request

java.lang.AssertionError
	at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setObject(SQLServerPreparedStatement.java:1693)
	at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setObjectNoType(SQLServerPreparedStatement.java:1530)
	at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setObject(SQLServerPreparedStatement.java:1539)
	at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.setObject(HikariProxyPreparedStatement.java)
	at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:402)
	at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:232)
	at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:147)
	at org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.setValues(PreparedStatementCreatorFactory.java:278)
	at org.springframework.jdbc.core.PreparedStatementCreatorFactory$PreparedStatementCreatorImpl.createPreparedStatement(PreparedStatementCreatorFactory.java:236)
	at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:601)
	at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:879)
	at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(NamedParameterJdbcTemplate.java:335)
	at com.andrunevchyn.test.MyDao.save(MyDao.java:73)

and you have no idea whats wrong on request just check your parameters. In my case I didn’t notice I passed enum value instead name of that value.  Seems SpringJdbc doesn’t know how to convert enum to String ((. The same issue appears if you try pass value of Instant class instead java.sql.Timestamp

P.S.

Tested on Spring5, Java 9. Save method looks like

public int save(StatusEnum status) {
			
			String sql = "INSERT INTO MyTable(status)  VALUES (:status)";

			MapSqlParameterSource params = new MapSqlParameterSource();
			params.addValue("status", status);
			
			KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
			namedJdbcTemplate.update(sql, params, generatedKeyHolder, new String[] { "id" });
			int autoGeneratedId = generatedKeyHolder.getKey().intValue();

			return autoGeneratedId;

	}

should be

public int save(StatusEnum status) {
			
			String sql = "INSERT INTO MyTable(status)  VALUES (:status)";

			MapSqlParameterSource params = new MapSqlParameterSource();
			params.addValue("status", status.name());
			
			KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
			namedJdbcTemplate.update(sql, params, generatedKeyHolder, new String[] { "id" });
			int autoGeneratedId = generatedKeyHolder.getKey().intValue();

			return autoGeneratedId;

	}

 

 

Comments 0
There are currently no comments.