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 有好几个重构方法, 可以都写上也可以只写一种, 能实现效果就行;

我就只重写了 setNonNullParameter 和 getNullableResult (ResultSet版) 这两个;

相关推荐
钝挫力PROGRAMER12 小时前
开发踩坑记:MyBatis selectKey、空 SQL
数据库·sql·mybatis
自强的小白12 小时前
核心功能(Service接口)
java·mybatis
自强的小白18 小时前
mybatis-plus 的扩展功能
mybatis·mybatis_plus
自强的小白19 小时前
MYbatis-plus(自定义sql)
java·sql·mybatis
\光辉岁月/1 天前
6.mybatisplus学习-BaseMapper、Service、常用注解
java·mybatis·mybatisplus
\光辉岁月/2 天前
1.mybatis学习-基础
学习·mybatis
代码什么用2 天前
在WEB中的应用
mybatis
牧瀬クリスだ2 天前
Mybatis-Plus:让CRUD快如闪电
java·spring boot·spring·tomcat·mybatis·yml
九皇叔叔3 天前
【09】SpringBoot4 MyBatisPlus 增删改查(CRUD)
java·mybatis·mybatisplus
景熙55233 天前
JDBC 详解:从原理到实战(含完整可运行 Demo)
java·spring·tomcat·mybatis·jdbc