Mybatis 使用 SQLite 不支持 LocalDateTime 的解决方案
增加一个 TypeHandler
就好辣
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
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 java.util.Calendar;
import java.util.Date;
/**
* @author Mr.X
* @since 2022-07-30 12:19
*/
@Component
public class LocalDateTimeHandler extends BaseTypeHandler<LocalDateTime> {
@Resource
private JacksonProperties jacksonProperties;
@Override
public void setNonNullParameter(@NonNull PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
ps.setObject(i, parameter);
}
@Override
public LocalDateTime getNullableResult(@NonNull ResultSet rs, String columnName) throws SQLException {
long aLong = rs.getLong(columnName);
return aLong < 167375 ? str2LocalDateTime(rs.getString(columnName)) : ts2LocalDateTime(aLong);
}
@Override
public LocalDateTime getNullableResult(@NonNull ResultSet rs, int columnIndex) throws SQLException {
return ts2LocalDateTime(rs.getLong(columnIndex));
}
@Override
public LocalDateTime getNullableResult(@NonNull CallableStatement cs, int columnIndex) throws SQLException {
return ts2LocalDateTime(cs.getLong(columnIndex));
}
@Nullable
private LocalDateTime str2LocalDateTime(@Nullable String time) {
if (time == null) return null;
return LocalDateTime.parse(time, DateTimeFormatter.ofPattern(jacksonProperties.getDateFormat()));
}
@NonNull
private LocalDateTime ts2LocalDateTime(@NonNull Long timeStamp) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(timeStamp));
return LocalDateTime.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));
}
}
本文作者:博麗靈夢
本文链接:https://www.cnblogs.com/Hakurei-Reimu-Zh/p/16534759.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)