Spring JodaTime和BeanPropertySqlParameterSource
情况是这样的: PostgreSQL数据库表有一个字段Spring JodaTime和BeanPropertySqlParameterSource,spring,postgresql,datetime,jodatime,spring-jdbc,Spring,Postgresql,Datetime,Jodatime,Spring Jdbc,情况是这样的: PostgreSQL数据库表有一个字段dateAdded,它是timestamp Pojo模型对象将此字段映射为 class MyModel{ org.joda.time.DateTime dateAdded; } 我的Dao实现在Spring JDBC模板中,如下所示: SqlParameterSource parameters = new BeanPropertySqlParameterSource(patient); jdbcInsert.execute(para
dateAdded
,它是timestamp
Pojo模型对象将此字段映射为
class MyModel{
org.joda.time.DateTime dateAdded;
}
我的Dao实现在Spring JDBC模板中,如下所示:
SqlParameterSource parameters = new BeanPropertySqlParameterSource(patient);
jdbcInsert.execute(parameters);
我从客户端读取模型,并使用@model
构建对象。到目前为止一切都很好。当我执行此操作时,数据库抛出一个异常,表示:[编辑Erwin]:结果表明异常不是来自数据库 我不想通过实现完整的INSERT语句来手动进行格式化,因为其中涉及许多字段 这里最好的解决方案是什么?是否有方法在所有调用中配置
DateTime
的toString()
。我还想过从DateTime创建一个继承类,但是。。。嗯。。这是决赛
--
编辑
根据Erwin的说法,我通过插入一个虚拟表来测试日期时间值“2011-10-10T21:55:19.790+03:00”,它正在工作。但是无法使用JDBC。与JDBC驱动程序相关的内容?这里的问题是
JdbcTemplate
正在使用准备好的语句,然后绑定值。该字段是timestamp类型,因此需要将其设置为java.sql.Date
。在本例中,spring调用了通用的setObject
方法,将Joda TimeDateTime
实例传递给它。驱动程序不知道如何将其转换为java.sql.Date
——因此出现了错误
要解决此问题,可以扩展BeanPropertySqlParameterSource
覆盖getValue
方法。如果对象的类型是joda.time.DateTime
将其转换为java.util.Date
对象并返回它。这应该可以解决问题
class CustomBeanPropertySqlParameterSource extends BeanPropertySqlParameterSource {
@Override
Object getValue(String paramName) {
Object result = super.getValue(paramName);
if (result instanceof DateTime) {
return ((DateTime) result).toDate();
} else {
return result;
}
}
}
“2011-10-10T21:55:19.790+03:00”在我知道的所有版本的PostgreSQL中对时间戳都有效。你的版本是什么?您的SQL语句中是否缺少时间戳(我在这里添加的)周围的单引号?如果不是这样的话,你能给我们看一下相应的postgresql server日志吗?这样可以消除混淆。Postgres 9。问题是,我不是在这里写SQL Insert语句。我只是构建模型对象,使用BeanPropertySqlParameterSource包装它,并将其推送到Spring JDBC SimpleJdbcInsert对象。这将在内部处理SQL插入。你是对的。我刚刚使用一个虚拟表测试了相同的值,它正在工作。这太奇怪了。Erwin花了一段时间才找到Pgsql server日志。此操作没有被注销的错误消息。无法帮助您完成JDBC部分,我的专长在于postgresql。如果JDBC的语法错误,您可以通过提供类似于
'2011-10-1021:55:19.790+03:00'
的替代语法来解决这个问题。T
,虽然完全合法,但这是不寻常的。谢谢欧文。希望别人有答案。正如你所说,我也觉得很奇怪。
class CustomBeanPropertySqlParameterSource extends BeanPropertySqlParameterSource {
@Override
Object getValue(String paramName) {
Object result = super.getValue(paramName);
if (result instanceof DateTime) {
return ((DateTime) result).toDate();
} else {
return result;
}
}
}