Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting DateTime from ResultSet in JdbcTemplate

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.

like image 267
Bohn Avatar asked Aug 10 '11 20:08

Bohn


2 Answers

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())

like image 75
skaffman Avatar answered Sep 21 '22 23:09

skaffman


Try with:

variant.setDiscoveryDate(new DateTime(rs.getTimestamp("discovery_dt_tm").getTime()));
like image 23
Jonas Avatar answered Sep 22 '22 23:09

Jonas