MybatisPlus 2.3.1中自定义TypeHandler问题

Java Long 类型和 SQL TIMESTAMP 类型转换

TimestampToLongHandler.java

@MappedJdbcTypes(JdbcType.TIMESTAMP)
@MappedTypes(Long.class)
public class TimestampToLongHandler<T> extends BaseTypeHandler<Long> {

    public TimestampToLongHandler() {
    }

    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Long t, JdbcType jdbcType) throws SQLException {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(t), ZoneOffset.ofHours(8));
        preparedStatement.setString(i, localDateTime.toString());
    }

    public Long getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String time = resultSet.getString(s);
        return Timestamp.valueOf(time).getTime(); //毫秒
    }

    public Long getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String time = resultSet.getString(i);
        return Timestamp.valueOf(time).getTime(); //毫秒
    }

    public Long getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String time = callableStatement.getString(i);
        return Timestamp.valueOf(time).getTime(); //毫秒
    }
}

插入的时候配置

   @TableField(el = "updateTime,javaType=Long,jdbcType=TIMESTAMP,typeHandler=cn.webank.hsfs.common.mybatis.TimestampToLongHandler")
    private Long updateTime;

查询时候👆的配置不起作用,需要单独再配置
参考 issue: https://github.com/baomidou/mybatis-plus/issues/357#issuecomment-706543587
直接注入这个typeHandlersPackage属性

    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        .......
        <property name="typeHandlersPackage" value="xxxxxx.mybatis.typehandler"/>
        ......
    </bean> 

sql中的timestamp 是毫秒类型的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。