MybaitsPlus字段自动转换

文章介绍了在MyBatis中如何处理Date类型数据与Long类型数据库之间的转换,使用了DateLongTypeHandler自定义类型处理器,以及处理查询结果时将Long型时间戳转换回Date对象的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实体是Date类型,数据库是Long类型,
通过转换,保存Date转成Long存入,查询从Long转成Date
可以是任意类型的转换

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import java.io.Serializable;
import java.util.Date;

import com.handler.DateLongTypeHandler;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * <p>
 * 运行计划
 * </p>
 * @since 2023-11-08
 */
@Data
@Accessors(chain = true)
@TableName("hss_plan")
public class HssPlanEntity extends Model<HssPlanEntity> implements Serializable {

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    /**
     * hss_type.id
     */
    private Long typeId;
    /**
     * hss_equipment.id
     */
    private Long equipmentId;
    /**
     * 生效时间:0表示没有生效时间限制
     */
    @TableField(typeHandler = DateLongTypeHandler.class)
    private Date startTime;
}

转换handler类


import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.tecloman.cloud.common.redis.model.RedisUserModel;
import com.tecloman.cloud.common.server.utils.DateUtils;
import org.apache.ibatis.type.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.TimeZone;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

@Component
@MappedTypes({Date.class})
@MappedJdbcTypes({JdbcType.BIGINT})
public class DateLongTypeHandler extends BaseTypeHandler<Date> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null) {
            if (jdbcType == null) {
                throw new TypeException(
                        "JDBC requires that the JdbcType must be specified for all nullable parameters.");
            }
            try {
                ps.setNull(i, jdbcType.TYPE_CODE);
            } catch (SQLException e) {
                throw new TypeException(
                        "Error setting null for parameter #"
                                + i
                                + " with JdbcType "
                                + jdbcType
                                + " . "
                                + "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. "
                                + "Cause: " + e, e);
            }
        } else {
            ps.setLong(i, parameter.getTime() / 1000);
        }
    }

    // 需要转成用户时区的实体字段
    private final String[] userTimezoneColumn = {"create_time"};

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
        long res = rs.getLong(columnName);
        if (res == 0) {
            return null;
        }
        Date d;
        try {
            d = new Date(res * 1000);
        } catch (Exception ex) {
            d = new Date(res);
        }
        return d;
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        long res = rs.getLong(columnIndex);
        if (res == 0) {
            return null;
        }
        Date d;
        try {
            d = new Date(res * 1000);
        } catch (Exception ex) {
            d = new Date(res);
        }
        return d;
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        long res = cs.getLong(columnIndex);
        if (res == 0) {
            return null;
        }
        Date d;
        try {
            d = new Date(res * 1000);
        } catch (Exception ex) {
            d = new Date(res);
        }
        return d;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值