Java JDBC RowMapper:将 MSSQL Server datetimeoffset 转换为 Java OffsetDateTime

问题描述 投票:0回答:1

我正在使用 JDBC 模板从 MS SQL Server / Azure 中的数据库检索数据。我有我的 注册日期作为 SQL 中的 datetimeoffset。相应的 RowMapper / ResultSet 方法是什么,转换为 Java OffsetDateTime ?

请参阅最后一行:

SQL:

CREATE TABLE [dbo].[Customer](
    [CustomerId] [int] IDENTITY(1,1) NOT NULL,
    [FirstName] [varchar](255) NOT NULL,
    [employeeid] [int] NOT NULL,
    [EnrollmentAmount] [decimal](10, 2) NULL,
    [ActiveFlag] [bit] NULL,
    [EnrollmentDate] [datetimeoffset](7) NULL,  -- << this coloumn

Java:

@Data
public class CustomerGetResponse {
    private int customerId;
    private String firstName;
    private int employeeId;
    private BigDecimal enrollmentAmount;
    private boolean activeFlag;
    private OffsetDateTime enrollmentDate;  
}

public class CustomerGetMapper implements RowMapper<CustomerGetResponse> {
    public CustomerGetResponse mapRow(ResultSet rs, int rowNum) throws SQLException {
        CustomerGetResponse customer = new CustomerGetResponse();
        customer.setCustomerId(rs.getInt("CustomerId"));
        customer.setFirstName(rs.getString("FirstName"));
        customer.setFeeAmount(rs.getBigDecimal("EnrollmentAmount"));
        customer.setActiveFlag(rs.getBoolean("ActiveFlag"));
        customer.setEnrollmentDate(rs.); -- << trying to figure out correct ResultSet method
        return customer;
    }

注意:BeanPropertyRowMapper.newInstance(CustomerGetResponse.class) 似乎做得很好,(不确定它内部做什么),但尝试使用手动 RowMapper。

参考问题:SQL Server数据库中java.time.OffsetDateTime的列类型是什么?

java sql-server spring-boot jdbc azure-sql-database
1个回答
0
投票

“标准”的做法是:

OffsetDateTime offset = rs.getObject(1, OffsetDateTime.class);

可以使用的几个替代方案:

import microsoft.sql.DateTimeOffset;
...
DateTimeOffset dto = (DateTimeOffset) rs.getObject(1);
DateTimeOffset dto = rs.getObject(1, DateTimeOffset.class);
DateTimeOffset dto = ((SQLServerResultSet)rs).getDateTimeOffset(1);

return dto != null ? dto.getOffsetDateTime(): null; //Careful with nulls!

第一个版本是最安全的,避免了强制转换,而其他版本则使用具体的微软实现类。

这些已使用 microsoft jdbc 驱动程序版本 9.1.1 进行测试,您的里程可能会因旧版本而异。 另外,一般要注意时区处理,有很多陷阱以及丢失来自数据库和返回数据库的信息的方法!

© www.soinside.com 2019 - 2024. All rights reserved.