JodaTime和BeanPropertySqlParameterSource

Fir*_*mir 5 postgresql spring datetime spring-jdbc jodatime

情况是这样的:

PostgreSQL数据库表中有一个字段dateAddedtimestamp

Pojo模型对象将此字段映射为

class MyModel{
   org.joda.time.DateTime dateAdded;

}
Run Code Online (Sandbox Code Playgroud)

我的Dao实现是在Spring JDBC Template中,它如下:

SqlParameterSource parameters = new BeanPropertySqlParameterSource(patient);
jdbcInsert.execute(parameters);
Run Code Online (Sandbox Code Playgroud)

我从客户端读取模型并使用构建对象@Model.到目前为止一切都很好.当我执行此操作时,数据库抛出一个异常说:
[编辑Erwin]:结果异常不是来自数据库.

org.postgresql.util.PSQLException: Bad value for type timestamp : 2011-10-10T21:55:19.790+03:00
Run Code Online (Sandbox Code Playgroud)

我不想通过实现完整的INSERT语句手动进行格式化,因为涉及许多字段.

这里最好的解决方案是什么?有没有配置方式toString()DateTime所有呼叫.我还想过从DateTime创建一个继承的类但是... mmhh ..这是一个决赛.

-

编辑

Per Erwin,我通过插入虚拟表来测试DateTime值'2011-10-10T21:55:19.790 + 03:00'并且它正在工作.但无法使用JDBC.与JDBC驱动程序有关的东西?

gka*_*mal 13

这里的问题是JDBCTemplate正在使用预准备语句然后绑定值.有问题的字段是时间戳类型 - 因此需要将其设置为java.sql.Date.在这种情况下,spring调用泛型setObject方法,将joda时间DateTime实例传递给它.驱动程序不知道如何将其转换为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 != null && result instanceof DateTime) {
        return ((DateTime)result).toDate();
     } else {
        return result;
     }

  }
}
Run Code Online (Sandbox Code Playgroud)