How to use JdbcTemplate.update with KeyHolder?

I have a method that saves the user to the database and returns an automatically generated identifier:

public int save(User user) {
    KeyHolder holder = new GeneratedKeyHolder();
    jdbcTemplate.update(SAVE_USER, user.getParams(), holder);
    return holder.getKey().intValue();
}

public Object[] getParams() {
        return new Object[]{
                email, // String email
                password}; // String password
}

SAVE_USER = INSERT INTO user (email, password) VALUES (?, ?)

When I try to execute a method, I get an exception:

Request processing failed; nested exception is org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; 
SQL [INSERT INTO user (email, password) VALUES (?, ?)]; Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException
+4
source share
1 answer

It looks like you are using Spring. The JdbcTemplate interface is slightly different depending on the version. However, I do not know if there is a method signature that matches what I think your intended call means:

update(String sql, Object[] args, KeyHolder keyHolder)

As with Spring 3, only:

update(PreparedStatementCreator psc) 
update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder) 
update(PreparedStatementCreator psc, PreparedStatementSetter pss) 
update(java.lang.String sql) 
update(java.lang.String sql, java.lang.Object[] args, int[] argTypes) 
update(String sql, PreparedStatementSetter pss) 

/* and this is the one I think you're matching */
update(java.lang.String sql, java.lang.Object... args)  

, , , , . SQL. KeyHolder , params . , , .

KeyHolder, , , :

update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder) 
+2

Source: https://habr.com/ru/post/1529459/


All Articles