Java Long 类型和 SQL TIMESTAMP 类型转换
TimestampToLongHandler.java
@MappedJdbcTypes(JdbcType.TIMESTAMP)
@MappedTypes(Long.class)
public class TimestampToLongHandler extends BaseTypeHandler {
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属性
.......
......
sql中的timestamp 是毫秒类型的