SQLite 不支持 LocalDateTime

需求描述

MyBatis-Plus 使用 SQLite 不支持 LocalDateTime;

解决方案

config 包下增加一个自定义 TypeHandler, 代码如下:

java 复制代码
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 lombok.NonNull;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

/**
* @author hqp
* @date 2023/8/30 14:27
*/
@Component
public class LocalDateTimeHandler extends BaseTypeHandler<LocalDateTime> {

  private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

  /**
   * 用途: 将 Java 对象 (LocalDateTime) 转换为 JDBC 参数类型 (通常为 Timestamp) 并设置到 PreparedStatement 中
   */
  @Override
  public void setNonNullParameter(PreparedStatement preparedStatement, int i,
      LocalDateTime localDateTime, JdbcType jdbcType) throws SQLException {
    preparedStatement.setObject(i, localDateTime.format(FORMATTER));
  }

  /**
   * 用途: 从 ResultSet 中读取数据库字段并转换为 Java 对象 (LocalDateTime)
   */
  @Override
  public LocalDateTime getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
  if (resultSet.getString(columnName) == null) {
      return null;
    } else {
      return ts2LocalDateTime(resultSet.getString(columnName));
    }
  }

  /**
   * 用途‌:从 ResultSet 中按列索引读取并转换为 Java 对象 (LocalDateTime)
   */
  @Override
  public LocalDateTime getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
  return null;
  }

  /**
   * 用途‌:从存储过程的输出参数中读取并转换为 Java 对象 (LocalDateTime)
   */
  @Override
  public LocalDateTime getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
    return null;
  }

  @NonNull
  private LocalDateTime ts2LocalDateTime(@NonNull String dateTime) {
    return LocalDateTime.parse(dateTime, FORMATTER);
  }
}

继承 BaseTypeHandler<LocalDateTime> 类的4个核心方法里面 getNullableResult 有好几个重构方法, 可以都写上也可以只写一种, 能实现效果就行;

我就只重写了 setNonNullParametergetNullableResult (ResultSet版) 这两个;

相关推荐
侠客行03175 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
老毛肚7 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
ggabb8 小时前
中文的全息之美:字音藏道,字里见宇宙
sqlite
WHD30610 小时前
苏州数据库(SQL Oracle)文件损坏修复
hadoop·sql·sqlite·flume·memcached
玄同76517 小时前
SQLite + LLM:大模型应用落地的轻量级数据存储方案
jvm·数据库·人工智能·python·语言模型·sqlite·知识图谱
独断万古他化18 小时前
【SSM开发实战:博客系统】(三)核心业务功能开发与安全加密实现
spring boot·spring·mybatis·博客系统·加密
ggabb20 小时前
中文的精确与意境,从来都不是英文能比肩的
sqlite
fengxin_rou21 小时前
[Redis从零到精通|第四篇]:缓存穿透、雪崩、击穿
java·redis·缓存·mybatis·idea·多线程
老毛肚1 天前
MyBatis插件原理及Spring集成
java·spring·mybatis
orange_tt1 天前
Djiango配置Celery
数据库·sqlite