You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JDBC RowMapper中将MSSQL datetimeoffset转为Java OffsetDateTime

解决方案

对于SQL Server的datetimeoffset类型,直接使用ResultSet的getObject()方法并指定目标类型为OffsetDateTime.class即可完成转换,这是最简洁且官方推荐的方式。

注意事项

  • 确保使用Microsoft JDBC Driver for SQL Server 9.0及以上版本,该版本开始完善支持datetimeoffset与OffsetDateTime的直接映射
  • 若字段可能为空,无需额外处理,getObject()会返回null,符合实体类字段的可空定义

修改后的完整RowMapper代码

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.setEnrollmentAmount(rs.getBigDecimal("EnrollmentAmount")); // 修正方法名与实体类字段匹配
        customer.setActiveFlag(rs.getBoolean("ActiveFlag"));
        // 核心转换代码
        customer.setEnrollmentDate(rs.getObject("EnrollmentDate", OffsetDateTime.class));
        return customer;
    }
}

备选方案(手动解析)

如果因驱动版本限制无法使用getObject(),可以先获取字符串格式的datetimeoffset值,再手动解析:

String dateStr = rs.getString("EnrollmentDate");
customer.setEnrollmentDate(dateStr != null ? OffsetDateTime.parse(dateStr) : null);

但该方式代码冗余,且不如getObject()稳定,优先推荐前者。


内容的提问来源于stack exchange,提问作者mattsmith5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:12:29