如何修改我的`@ SQLUpdate`以将`Joda``DateTime`对象转换为`h2`可读时间戳?

时间:2015-06-06 00:37:56

标签: java datetime jodatime h2 jdbi

如何修改var x = function (){ /* doing something for eventually a looong time */ } x.kill() 以将@SQLUpdate Joda对象转换为DateTime - 可读时间戳?

我有一个DAO对象h2,使用MyDao方法。

insert

以下是public interface MyDao extends Transactional<MyDao> { @SqlUpdate( "INSERT INTO my_table "(id, original_date, later_date)" + "VALUES (:id, :originalDate, :laterDate)" void insert(@BindBean MyObject myObject); }

MyObject

import java.util.UUID; import org.joda.time.DateTime; public class MyObject { private UUID id; private DateTime originalDate; private DateTime laterDate; public MyObject(UUID id, DateTime originalDate, DateTime laterDate) { this.id = id; this.originalDate = originalDate; this.laterDate = laterDate; } } 文件中(我使用http://www.liquibase.org/xml/ns/dbchangelog),我有:

migrations.xml

这是我的测试:

<column name="original_date" type="timestamp">
    <constraints nullable="false"/>
</column>
<column name="later_date" type="timestamp">
    <constraints nullable="false"/>
</column>

我试过测试一下,但是出现了这样的错误:

@Test
public void test() {
    DateTime dt = new DateTime(2015, 5, 29, 8, 34);
    UUID uuid = new UUID(5, 8);
    MyObject myObject = new MyObject(uuid, dt, dt);
    mydao.insert(myObject)
    // assertEquals and other code here
}

1 个答案:

答案 0 :(得分:3)

我们可以通过将参数工厂注册到DBI来实现。

public class DateTimeArgumentFactory implements ArgumentFactory<DateTime> {
    @Override
    public boolean accepts(Class<?> expectedType, Object value, StatementContext ctx) {
        return value != null && DateTime.class.isAssignableFrom(value.getClass());
    }

    @Override
    public Argument build(Class<?> expectedType, final DateTime value, StatementContext ctx) {
        return new Argument() {
            @Override
            public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
                statement.setTimestamp(position, new java.sql.Timestamp(value.getMillis()));
            }
        };
    }
}

将此参数工厂注册到DBI,

  dbi.registerArgumentFactory(new DateTimeArgumentFactory());

这将自动将DateTime转换为sql TimeStamp。