getting DateTime from ResultSet in JdbcTemplate

时光怂恿深爱的人放手 提交于 2019-12-06 01:26:59

问题


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.


回答1:


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




回答2:


Try with:

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


来源:https://stackoverflow.com/questions/7017268/getting-datetime-from-resultset-in-jdbctemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!