1

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?

Noremac
  • 3,445
  • 5
  • 34
  • 62
  • possible duplicate of [How to execute IN() SQL queries with Spring's JDBCTemplate effectivly?](http://stackoverflow.com/questions/1327074/how-to-execute-in-sql-queries-with-springs-jdbctemplate-effectivly) – aglassman Apr 04 '14 at 15:06
  • Not a duplicate. This question is asking about advanced functionality: how to customize how the object is handled in the IN clause. The referenced question answers for basic functionality. – Noremac Apr 04 '14 at 16:47
  • My bad, I should have read the question closer. – aglassman Apr 04 '14 at 19:23

1 Answers1

2

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

  • This is the best approach I've seen or thought of. However, since my need for this functionality is quite isolated (a single query) I'm opting for a simple for loop to create a new List. – Noremac Apr 04 '14 at 16:49