pavel_kazlou
pavel_kazlou

Reputation: 2046

spring jdbc template custom type

In my project I use Spring 3.0 JdbcTemplate to implement DAO classes. It provides convenient methods like query(...), update(...) etc. These methods accept objects as arguments to bind to the query. In javadoc it is stated that it is left to the PreparedStatement to guess the corresponding SQL type. So when using primitives or wrappers it is simple.

But in my code I use special classes for id representation. For example UserId. It has public method to get its integer value - getInt(). Right now I have to use

userId.getInt()

every time I need to pass instance of UserId to the JdbcTemplate query. If I forget and write just

userId

I obviously get SQLException, as my UserId object can't be consumed by prepared statement (here are the rules to map Object type to corresponding SQL type). But this type of error can't be spotted during compilation (as JdbcTemplate accepts Object as parameter), which makes bugs introducing easy.

Is there any way I can avoid calling .getInt() and just pass my UserId object into the query?

Upvotes: 0

Views: 2127

Answers (1)

artbristol
artbristol

Reputation: 32407

I imagine you could override org.springframework.jdbc.core.JdbcTemplate.newArgPreparedStatementSetter(Object[]) with a new version of org.springframework.jdbc.core.ArgPreparedStatementSetter that checks (in doSetValue) whether the Object argValue is of your special UserId type.

Upvotes: 1

Related Questions