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

相关推荐
用户8307196840823 小时前
秒杀面试!MyBatis-Spring-Boot 初始化流程深度拆解
spring boot·mybatis
8***f3955 小时前
Spring 中使用Mybatis,超详细
spring·tomcat·mybatis
xj7573065335 小时前
《精通Django》 第五章 Django管理后台
数据库·django·sqlite
w***76555 小时前
Spring Boot 集成 MyBatis 全面讲解
spring boot·后端·mybatis
kaizq16 小时前
AI-MCP-SQLite-SSE本地服务及CherryStudio便捷应用
python·sqlite·llm·sse·mcp·cherry studio·fastmcp
张较瘦_18 小时前
SpringBoot3 | MyBatis-Plus 搞定宠物管理:从0到1实现增删改查
mybatis·宠物
代码游侠1 天前
应用——智能配电箱监控系统
linux·服务器·数据库·笔记·算法·sqlite
沙白猿1 天前
Redis报错:A bean with that name has already been defined in class path resource
spring boot·redis·mybatis
七夜zippoe1 天前
领域驱动设计在Python中的实现:从理论到生产级实践
数据库·python·sqlite·ddd·pydantic