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

相关推荐
敲代码的嘎仔5 小时前
Java后端面试——SSM框架面试题
java·面试·职场和发展·mybatis·ssm·springboot·八股
ruanyongjing5 小时前
SpringBoot3 整合 Mybatis 完整版
mybatis
小江的记录本9 小时前
【MyBatis-Plus】Spring Boot + MyBatis-Plus 进行各种数据库操作(附完整 CRUD 项目代码示例)
java·前端·数据库·spring boot·后端·sql·mybatis
AI成长日志10 小时前
【实用工具教程】数据库基础操作实战:SQLite/MySQL连接、CRUD操作与查询优化
数据库·mysql·sqlite
小江的记录本11 小时前
【MyBatis-Plus】MyBatis-Plus的核心特性、条件构造器、分页插件、乐观锁插件
java·前端·spring boot·后端·sql·tomcat·mybatis
码界奇点13 小时前
基于Spring Boot和MyBatis的图书管理系统设计与实现
spring boot·后端·车载系统·毕业设计·mybatis·源代码管理
Javatutouhouduan15 小时前
SpringBoot如何快速精通?
java·spring boot·mybatis·java面试·后端开发·java编程·java程序员
iMingzhen17 小时前
不想引入 Redis,我用一张 SQLite 表实现了消息队列
数据库·redis·ai·sqlite
稻草猫.17 小时前
MyBatis进阶:动态SQL与MyBatis Generator插件使用
java·数据库·后端·spring·mvc·mybatis
小王不爱笑1321 天前
MyBatis 执行流程源码级深度解析:从 Mapper 接口到 SQL 执行的全链路逻辑
数据库·sql·mybatis