美文网首页
MybatisPlus 2.3.1中自定义TypeHandler

MybatisPlus 2.3.1中自定义TypeHandler

作者: cain_li | 来源:发表于2020-10-10 20:51 被阅读0次

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 是毫秒类型的

相关文章

网友评论

      本文标题:MybatisPlus 2.3.1中自定义TypeHandler

      本文链接:https://www.haomeiwen.com/subject/iggjpktx.html