Question

I have a method which save the user in DB and return auto generated id:

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 trying to execute a method, I'm getting 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
Was it helpful?

Solution

Looks like you're using Spring. Depending on the version, the JdbcTemplate interface varies a bit. Still, in no version I know of is there a method signature that matches what I think your intended call is:

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

As of Spring 3, there's 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)  

Unfortunately, even though your call matches that last method's signature, it doesn't do what I think you're looking for. It tries to apply each argument as an individual argument to the SQL statement. Your KeyHolder is out of place in that circumstance, and the params array would have to be split out as individual parameters. Basically, that method won't work for what you're doing.

If you want to use the KeyHolder, I think you need to change your approach to use this method:

update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top