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

MyBatis映射毫秒级Timestamp如何转换为指定格式的常规时间戳

MyBatis Timestamp格式映射问题解决方案

配置失效原因

你添加的jdbcType=TIMESTAMP仅用于指定MyBatis执行JDBC操作时的字段类型匹配规则,不会干预时间类型的序列化输出逻辑,你看到的毫秒值本质是JSON序列化框架(默认多为Jackson)对java.sql.Timestamp等时间类型的默认处理逻辑,和JDBC类型配置无关。

可行实现方案

  • 方案1:Spring Boot项目全局序列化配置(改动最小)
    若你的项目基于Spring Boot构建,直接在application.yml/application.properties中添加Jackson序列化规则即可全局生效:
    spring:
      jackson:
        # 匹配你需要的带纳秒、时区的ISO 8601格式
        date-format: yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX
        time-zone: 你的业务时区(比如GMT+8、UTC等)
        serialization:
          # 关闭时间转毫秒值的默认逻辑
          write-dates-as-timestamps: false
    
  • 方案2:MyBatis全局自定义TypeHandler处理
    若你需要在MyBatis映射层面直接完成格式转换,自定义TypeHandler实现映射逻辑:
    1. 编写自定义TypeHandler
    import org.apache.ibatis.type.BaseTypeHandler;
    import org.apache.ibatis.type.JdbcType;
    import org.apache.ibatis.type.MappedJdbcTypes;
    import org.apache.ibatis.type.MappedTypes;
    import java.sql.*;
    import java.time.OffsetDateTime;
    import java.time.format.DateTimeFormatter;
    
    @MappedTypes(OffsetDateTime.class)
    @MappedJdbcTypes(JdbcType.TIMESTAMP)
    public class CustomOffsetDateTimeHandler extends BaseTypeHandler<OffsetDateTime> {
        // 直接使用标准ISO_OFFSET_DATE_TIME formatter,匹配你需要的输出格式
        private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    
        @Override
        public void setNonNullParameter(PreparedStatement ps, int i, OffsetDateTime parameter, JdbcType jdbcType) throws SQLException {
            ps.setObject(i, parameter);
        }
    
        @Override
        public OffsetDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
            return rs.getObject(columnName, OffsetDateTime.class);
        }
    
        @Override
        public OffsetDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
            return rs.getObject(columnIndex, OffsetDateTime.class);
        }
    
        @Override
        public OffsetDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
            return cs.getObject(columnIndex, OffsetDateTime.class);
        }
    }
    
    1. 在MyBatis配置中注册该处理器
    <configuration>
      <typeHandlers>
        <typeHandler handler="你的包路径.CustomOffsetDateTimeHandler"/>
      </typeHandlers>
    </configuration>
    
    1. 把实体类对应时间字段的类型从Timestamp改为OffsetDateTime即可,映射后直接得到符合格式要求的时间对象。
  • 方案3:单字段指定转换规则(无需全局配置)
    若仅需要个别字段做格式转换,直接在对应ResultMap中指定typeHandler即可,也可自定义处理器直接将Timestamp转为你需要的格式字符串存入String类型字段。
    <result column="你的时间字段名" property="实体类字段名" typeHandler="你的包路径.CustomOffsetDateTimeHandler"/>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:00:00