从JdbcTemplate中的ResultSet获取DateTime [英] getting DateTime from ResultSet in JdbcTemplate
问题描述
我的列是类型TIMESTAMP,所以我的类的属性类型为Datetime像这样:
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;
}
现在在JdbcTemplate我想得到它,所以一些代码如下: / p>
now in JdbcTemplate I want to get it, so some code like this:
variant.setDiscoveryDate(rs.getTimestamp("discovery_dt_tm"));
哪些不工作,因为列的结果集的获取我找不到返回DateTime的东西,我只看到getDate或getTime。
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.
推荐答案
这是因为 DateTime
不是标准Java类型。如果您指的是JodaTime类型,请尝试以下方式:
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())
);
如果 rs.getTimestamp
返回 null
,所以你可能想把它分解成较小的语句,并为 null
添加检查。
This will break if rs.getTimestamp
returns null
, so you may want to break this up into smaller statements and add checks for null
.
注意,这可以更容易,因为 DateTime
的构造函数需要一个 java.util.Date
,其中 Timestamp
是以下子类:
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"))
);
但这也是错误的,因为 Timestamp
类(请参阅 javadoc for解释)
But it's also wrong, due to bad design of the Timestamp
class (see javadoc for explanation).
坚持第一个例子(使用 getTime()
)
Stick with the first example (with getTime()
)
这篇关于从JdbcTemplate中的ResultSet获取DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!