Mybatis custom LocalDateTime type processor handler

Table of contents

1 maven dependencies

2 LocalDateTimeTypeHandler


1 maven dependencies

		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-boot-starter</artifactId>
			<version>3.4.1</version>
		</dependency>

2 LocalDateTimeTypeHandler

Rewrite LocalDateTimeTypeHandler to solve the conversion problem of shardingsphere + mybatis LocalDateTime

package com.xudongbase.mybatis.handler;

import org.apache.ibatis.type.JdbcType;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * 重写LocalDateTimeTypeHandler ,解决shardingsphere + mybatis LocalDateTime转换问题
 *
 * @author xudongmaster
 */
@Component
public class LocalDateTimeTypeHandler extends org.apache.ibatis.type.LocalDateTimeTypeHandler {
    public LocalDateTimeTypeHandler() {
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i, new Timestamp(this.toTimeMillis(parameter)));
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnName);
        return sqlTimestamp != null ? this.toLocalDateTime(sqlTimestamp.getTime()) : null;
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
        return sqlTimestamp != null ? this.toLocalDateTime(sqlTimestamp.getTime()) : null;
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
        return sqlTimestamp != null ? this.toLocalDateTime(sqlTimestamp.getTime()) : null;
    }

    private long toTimeMillis(LocalDateTime dateTime) {
        return dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    private LocalDateTime toLocalDateTime(long timeMillis) {
        return new Date(timeMillis).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}

Xudongguai's personal space-Xudongguai's personal homepage-哔哩哔哔video哔哩哔哩 Xudongguai's personal space, providing video, audio, articles, news, favorites and other content shared by Xudongguai, follow Xudong Blame the account, know the UP note dynamics in the first time. The trough in life is not terrible, what is terrible is that you can't persist until the turning point in your life https://space.bilibili.com/484264966?spm_id_from=333.1007.0.0

Guess you like

Origin blog.csdn.net/qq_38974638/article/details/129762669