Inserting DATETIME’s with Spring’s JdbcTemplate and NamedParameterJdbcTemplate

Ran into another bit of trouble today that cost me another sizable chunk of time. When using Spring’s NamedParameterJdbcTemplate to insert into a DATETIME column, the following doesn’t work:

Your date will be happily insert, but you’ll be sad to know that the time component has been truncated to something like “2012-08-28 00:00:00.” Using Types.TIMESTAMP has the same effect.

Using Types.TIMESTAMP is actually correct, but the secret is that you have to wrap your java.util.Date in a java.sql.Date.

If you’re reaction is one of disappointment, then you’re feeling the same way I did.

For simple JdbcTemplates, there is sufficient behind the scenes magic that you don’t run into this kind of problem. The following works without any translations or other such boilerplate (making the above that much more … dissatisfying).

I leave you with a list of SQL types and their Java equivalents, which is how I finally solved my problem with NamedParameterJdbcTemplate.

 

Hi there, I'm Justin!

I like to teaching people about programming. Well, yeah, I guess it's obvious, I also like to write. Yes that was a Digital Underground reference.