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版) 这两个;

相关推荐
百锦再3 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
莫寒清3 天前
Mybatis的插件原理
面试·mybatis
kangzerun3 天前
SQLiteManager:一个优雅的Qt SQLite数据库操作类
数据库·qt·sqlite
用户5757303346243 天前
AIGC 时代数据库革命:告别手写 SQL,用自然语言驾驭 SQLite
sqlite
莫寒清3 天前
MyBatis 中动态 SQL 的作用
面试·mybatis
吹晚风吧3 天前
实现一个mybatis插件,方便在开发中清楚的看出sql的执行及执行耗时
java·sql·mybatis
码云数智-大飞3 天前
像写 SQL 一样搜索:dbVisitor 如何用 MyBatis 范式颠覆 ElasticSearch 开发
sql·elasticsearch·mybatis
Mr__Miss4 天前
mybatisPlus分页组件3.5.15版本报错解决方案
mybatis
无名-CODING4 天前
MyBatis中#{}和${}完全指南:从原理到实战
mybatis
鹿角片ljp4 天前
短信登录:基于 Session 实现(黑马点评实战)
java·服务器·spring boot·mybatis