I’d like to use scala’s implicit conversion in spring JdbcTemplate.
JdbcTemplate has following 2 methods :
jdbcTemplate.update(String sql, Object... params) // (1)
jdbcTemplate.update(String sql, PreparedStatementSetter pss) // (2)
PreparedStatementSetter is just an interface, and I’d like to just pass a function value to JdbcTemplate. That means I want to change it to be
JdbcTemplate.update(sql: String, setter: PreparedStatement => Unit) // (3)
What I did is create RichJdbcTemplate, as a wrapper of JdbcTemplate:
class RichJdbcTemplate(jdbcTemplate: JdbcTemplate) {
def update(sql: String, setter: PreparedStatement => Unit) {
jdbcTemplate.update(sql, new PreparedStatementSetter() {
def setValues(ps: PreparedStatement) {
setter(ps)
}
})
}
}
And I expected that every time if I call jdbcTemplate.update(sql, setter: PreparedStatement => Unit)
there would be an implicit conversion between jdbcTemplate and RichJdbcTemplate. But actually it does not do implicit conversion here. Because here the method conforms with the signature of jdbcTemplate.update(String sql, Object... params). That’s why there’s no implicit conversion here. Is there any other solution that could achieve this? Thanks.
Just give your method a different name; call it
updateWithFunctionor something.As you mention, the issue is that Scala doesn’t look for an implicit conversion because it find a method with the correct name and correct parameter types directly on
JdbcTemplate. The way around it is to use a name that it won’t find onJdbcTemplate.You could also do the wrapping explicitly,
new RichJdbcTemplate(jdbcTemplate).update(...), but that’s uglier.