比起想念来,千年又何其长。比起相见来,千年又何其短。|

博麗靈夢

园龄:4年7个月粉丝:15关注:0

Mybatis 使用 SQLite 不支持 LocalDateTime 的解决方案

增加一个 TypeHandler 就好辣

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * @author Mr.X
 * @since 2022-07-30 12:19
 */
@Component
public class LocalDateTimeHandler extends BaseTypeHandler<LocalDateTime> {

    @Resource
    private JacksonProperties jacksonProperties;

    @Override
    public void setNonNullParameter(@NonNull PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, parameter);
    }

    @Override
    public LocalDateTime getNullableResult(@NonNull ResultSet rs, String columnName) throws SQLException {
        long aLong = rs.getLong(columnName);
        return aLong < 167375 ? str2LocalDateTime(rs.getString(columnName)) : ts2LocalDateTime(aLong);
    }

    @Override
    public LocalDateTime getNullableResult(@NonNull ResultSet rs, int columnIndex) throws SQLException {
        return ts2LocalDateTime(rs.getLong(columnIndex));
    }

    @Override
    public LocalDateTime getNullableResult(@NonNull CallableStatement cs, int columnIndex) throws SQLException {
        return ts2LocalDateTime(cs.getLong(columnIndex));
    }

    @Nullable
    private LocalDateTime str2LocalDateTime(@Nullable String time) {
        if (time == null) return null;
        return LocalDateTime.parse(time, DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat()));
    }

    @NonNull
    private LocalDateTime ts2LocalDateTime(@NonNull Long timeStamp) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date(timeStamp));
        return LocalDateTime.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));
    }

}

本文作者:博麗靈夢

本文链接:https://www.cnblogs.com/Hakurei-Reimu-Zh/p/16534759.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   博麗靈夢  阅读(1030)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起