jooq UTC localdatetime在保存和加载之间更改

问题描述

我的同事使用jooq创建了一个postgresql数据库。从那时起,我们使用字段和LocalDateTime.Now(ZoneOffset.UTC)的值创建了对象。当这些文件保存到该数据库中并在以后再次读取时,我们的数据对象中的几个小时发生了更改:

public class PlannedInvoice
{
    private UUID accountId;
    private LocalDateTime billingTime;
}

save方法类似于以下内容

LocalDateTime Now = LocalDateTime.Now(ZoneOffset.UTC);
UUID accountId = UUID.randomUUID();

PlannedinvoiceRecord record = plannedInvoiceService.create();
record.setAccountid(accountId.toString());
record.setBillingtime(Now.atOffset(ZoneOffset.UTC));
record.store();

读取方法如下:

return dsl.selectFrom(PLANNEDINVOICE)
        .where(PLANNEDINVOICE.ACCOUNTID.eq(accountId.toString()))
        .fetchOneInto(PlannedInvoice.class);

数据库当前使用timestamp with time zone,但我也很乐意将其替换为实际的LocalDateTime以避免这些问题(JOOQ supports this)!

当我们保存值LocalDateTime.of(2020,Month.AUGUST,13,0)时,它将在数据库中为2020-08-12 20:00:00-04。这似乎仍然正确。

数据库读取值似乎出了问题。读取方法后,billingTime的值为2020-08-12 20:00:00。在我看来,重建数据对象时,fetchOneInto会忽略时区。

那么,为什么在保存UTC值时进行转换,为什么在从数据库中读回时却不进行转换呢?这对我来说似乎很违反直觉。我宁愿完全避免任何时区转换。

解决方法

对我有用的是使用OffsetDateTime创建一个临时读取对象,然后使用withOffsetSameInstant(ZoneOffset.UTC).toLocalDateTime()对其进行转换。最终修复起来很容易。一开始,db和/或jooq会将数据转换为其他时区只是出于直觉。

这是新对象:

public class PlannedInvoiceWithOffset
{
    private UUID accountId;
    private OffsetDateTime billingTime;
}

用于创建所需数据对象并将时区调整为UTC的新构造函数:

public PlannedInvoice(PlannedInvoiceWithOffset tempObject)
{
    this.accountId = tempObject.getAccountId();
    this.billingTime = tempObject.getBillingTime().withOffsetSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

现在,我的读取方法如下:

public PlannedInvoice findByAccountId(UUID accountId)
{
    PlannedInvoiceWithOffset temp = dsl.selectFrom(PLANNEDINVOICE)
            .where(PLANNEDINVOICE.ACCOUNTID.eq(accountId.toString()))
            .fetchOneInto(PlannedInvoiceWithOffset.class);

    return new PlannedInvoice(temp);
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...