Question

I am using the super cool jdbcTemplate (more specifically the NamedParameterJdbcTemplate) for running a query with an IN clause. The list that I wish to query on however is an enum so I get the error: "incompatible data type in conversion".

I've noticed that every where I query with this enum I have to call toString() on it. Is there a way that I can tell jdbcTemplate to take the String value of the objects in the list?

Was it helpful?

Solution

Some kind of override is what you need I think:

public class MyNamedParameterJdbcTemplate extends NamedParameterJdbcTemplate {

    public MyNamedParameterJdbcTemplate(final DataSource dataSource) {
        super(dataSource);
    }

    @Override
    public <T> T execute(final String sql, final Map<String, ?> paramMap, final PreparedStatementCallback<T> action) throws DataAccessException {
        final Map<String, Object> newParam = new HashMap<>();
        for (final Map.Entry<String, ?> entry : paramMap.entrySet()) {
            if (entry instanceof Enum<?>) {
                // param is an enum
                newParam.put(entry.getKey(), ((Enum) entry).toString());
            } else {
                newParam.put(entry.getKey(), entry.getValue());
            }
        }
        return super.execute(sql, newParam, action);
    }
}

NB: not tested and Guava Maps.transformValues() is also an option

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top