Sharding jdbc分库分表与mybatis-plus一起使用与LocalDateTime冲突问题解决方案

本文讲述了在Java11和ShardingJDBC4.1.1与MyBatis-Plus3.4.0版本组合下,遇到LocalDateTime类型转换错误的问题。通过自定义LocalDateTimeTypeHandler解决了这一问题,涉及重写setNonNullParameter和getNullableResult方法。

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

Sharding jdbc分库分表与mybatis-plus一起使用与LocalDateTime冲突问题解决方案

背景

问题报错:Error attempting to get column ‘create_time’ from result set. Cause: java.sql.SQLFeatureNotSupportedException: getObject with type

java版本:java11

sharding jdbc版本:4.1.1

mybatis-plus版本:3.4.0

原因

Mybatis与Sharding版本某一个不支持LocalDateTime

解决

重写解析器

package com.ypsx.cart.server.infrastructure.handler;

import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * 描述:重写LocalDateTimeTypeHandler ,解决sharding_jdbc + ibatis LocalDateTime转换问题
 * Created by zjw on 2022/2/17 11:13
 */
@Component
public class LocalDateTimeTypeHandler extends org.apache.ibatis.type.LocalDateTimeTypeHandler {
    public LocalDateTimeTypeHandler() {
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i, new Timestamp(this.toTimeMillis(parameter)));
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnName);
        return sqlTimestamp != null ? this.toLocalDateTime(sqlTimestamp.getTime()) : null;
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
        return sqlTimestamp != null ? this.toLocalDateTime(sqlTimestamp.getTime()) : null;
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
        return sqlTimestamp != null ? this.toLocalDateTime(sqlTimestamp.getTime()) : null;
    }

    private long toTimeMillis(LocalDateTime dateTime) {
        return dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    private LocalDateTime toLocalDateTime(long timeMillis) {
        return new Date(timeMillis).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值