MyBatis转换器-时间与字符串

本文介绍了一个Java类型处理器(TimestampToStringTypeHandler)的实现,用于在MyBatis中处理从数据库获取的Timestamp字段,统一转换为特定格式的String,包括日期和时间。文章详细展示了如何设置和获取参数以及处理XML配置中的错误。
摘要由CSDN通过智能技术生成

背景:java字段类型为String,数据库类型为timestamp,需要统一处理时区

package xx.xx.xx;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeException;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Slf4j
public class TimestampToStringTypeHandler extends BaseTypeHandler<String> {
    private static final DateTimeFormatter LDT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter LDT_MILLIS_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    private static final ZoneId UTC = ZoneId.of("UTC");

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        // UTC时间写入
        LocalDateTime tm;
        try {
            if (parameter.length() == 19) {
                tm = LocalDateTime.parse(parameter, LDT_FORMATTER);
            } else if (parameter.length() == 23) {
                tm = LocalDateTime.parse(parameter, LDT_MILLIS_FORMATTER);
            } else {
                throw new TypeException("Error for parameter #" + i + " with JdbcType " + jdbcType + " . " +
                        "Cause: formatter unsupported, parameter=" + parameter);
            }
            ps.setTimestamp(i, new Timestamp(tm.toInstant(ZoneOffset.UTC).toEpochMilli()));
        } catch (Exception e) {
            throw new TypeException("Error for parameter #" + i + " with JdbcType " + jdbcType + " . " +
                    "Try parse timestamp for this parameter. " +
                    "Cause: " + e, e);
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp date = null;
        try {
            date = rs.getTimestamp(columnName);
        } catch (Exception e) {
            log.warn("unexpected: getTimestamp from ResultSet error, val={}", rs.getString(columnName), e);
        }
        return date == null ? null : LocalDateTime.ofInstant(date.toInstant(), UTC).format(LDT_FORMATTER);
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp date = null;
        try {
            date = rs.getTimestamp(columnIndex);
        } catch (Exception e) {
            log.warn("unexpected: getTimestamp from ResultSet error, val={}", rs.getString(columnIndex), e);
        }
        return date == null ? null : LocalDateTime.ofInstant(date.toInstant(), UTC).format(LDT_FORMATTER);
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp date = null;
        try {
            date = cs.getTimestamp(columnIndex);
        } catch (Exception e) {
            log.warn("unexpected: getTimestamp from ResultSet error, val={}", cs.getString(columnIndex), e);
        }
        return date == null ? null : LocalDateTime.ofInstant(date.toInstant(), UTC).format(LDT_FORMATTER);
    }
}

xml配置,xml报错注意MyBatis的标签顺序

  <typeHandlers>
    <typeHandler handler="xx.xx.xx.TimestampToStringTypeHandler"
                 javaType="java.lang.String" jdbcType="TIMESTAMP"/>
  </typeHandlers>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值