getting DateTime from ResultSet in JdbcTemplate

Bohn picture Bohn · Aug 10, 2011 · Viewed 25.3k times · Source

in database my column is of type TIMESTAMP, so my class has properties of type Datetime like this:

public void setDiscoveryDate(final DateTime discoveryDtTm) {
        this.discoveryDtTm = discoveryDtTm;
    }

now in JdbcTemplate I want to get it, so some code like this:

variant.setDiscoveryDate(rs.getTimestamp("discovery_dt_tm"));

which does Not work because column the get for resultset I could not find something that returns DateTime, I only saw either getDate or getTime.

Answer

skaffman picture skaffman · Aug 10, 2011

That's because DateTime is not a standard Java type. If you're referring to the JodaTime type, then try this:

variant.setDiscoveryDate(
   new DateTime(rs.getTimestamp("discovery_dt_tm").getTime())
);

This will break if rs.getTimestamp returns null, so you may want to break this up into smaller statements and add checks for null.

Note that this can be made easier, since DateTime's constructor takes a java.util.Date, which Timestamp is a subclass of:

variant.setDiscoveryDate(
   new DateTime(rs.getTimestamp("discovery_dt_tm"))
);

But it's also wrong, due to bad design of the Timestamp class (see javadoc for explanation).

Stick with the first example (with getTime())