MyBatis实现 Java 实体类和数据库中日期类型之间的转换(超详细)

背景

数据库存储的时间字段的类型是datetime
Java实体类的时间字段类型是Date
需求:响应前端的时间字段格式为”yyyy-MM-dd HH:mm:ss“

步骤

1、定义resultMap

定义 Java 对象和数据库表字段的对应关系,在 mapper.xml 文件中使用 #{属性名,jdbcType=数据库字段类型} 来进行参数传递和结果集映射,例如:

<resultMap id="userResultMap" type="User">
    <id column="id" property="id" jdbcType="INTEGER"/>
    <result column="name" property="name" jdbcType="VARCHAR"/>
    <result column="age" property="age" jdbcType="INTEGER"/>
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
</resultMap>

2、实体类时间字段上添加JsonFormat注解

@JsonFormat日期格式化你的pattern格式,timezone设置时区

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;

:时区也可以在application.yml或application.propertites配置文件中添加,一劳永逸,@JsonFormat就不需要配置timezone了

spring:
  jackson:
    time-zone: Asia/Shanghai

特殊解决方式如下

步骤1和2没有解决的话,继续如下三个步骤

3、自定义类型处理器(MyBatis支持)

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

public class MyDateTypeHandler implements TypeHandler<Date> {

    // 使用ThreadLocal来存储SimpleDateFormat的实例,确保线程安全
    private static final ThreadLocal<SimpleDateFormat> sdfHolder = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    @Override
    public void setParameter(PreparedStatement ps, int i, Date date, JdbcType jdbcType) throws SQLException {
        if (date == null) {
            ps.setNull(i, JdbcType.TIMESTAMP.TYPE_CODE);
        } else {
            // 从ThreadLocal获取SimpleDateFormat实例并设置参数
            ps.setString(i, sdfHolder.get().format(date));
        }
    }

    @Override
    public Date getResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp ts = rs.getTimestamp(columnName);
        return convertTimestampToDate(ts);
    }

    @Override
    public Date getResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp ts = rs.getTimestamp(columnIndex);
        return convertTimestampToDate(ts);
    }

    @Override
    public Date getResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp ts = cs.getTimestamp(columnIndex);
        return convertTimestampToDate(ts);
    }

    // 私有方法用于将Timestamp转换为Date
    private Date convertTimestampToDate(Timestamp ts) {
        return ts == null ? null : new Date(ts.getTime());
    }
}

4、将类型处理器Bean注入容器(在MyBatis配置类中)

@Configuration
@MapperScan({"com.example.mapper"})
public class MyBatisConfig {
    @Bean
    public TypeHandler<Date> myDateTypeHandler() {
        return new MyDateTypeHandler();
    }
}

5、mapper.xml文件中修改

<resultMap id="myResultMap" type="com.example.MyResultType">
  <id property="id" column="id" />
  <result property="createTime" column="create_time" typeHandler="com.example.MyDateTypeHandler"/>
</resultMap>

结果SUCCESS

在这里插入图片描述

结束语:当你在做你热爱的事情时,你永远不会感到疲惫。

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

热心码民阿振

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值