Mybatis-plus如何处理数据库字段是字符串类型的情况
一、背景
项目中遇到这样的情况,存在一个数据库表,我们需要用Mybatis对这个表进行操作。其中有时间字段,但是居然类型是varchar,这样我们编写的实体类里面对应的类型必须是String?还是LocalDateTime?
二、正确的处理方式
- 实体的字段类型仍然需要是LocalDateTime,这样才能保证我们时间操作的顺利,为了日后维护方便
- 编写字段转化处理的适配器类,在里面定义日期和字符创格式转化的格式,在实体类和时间字段上面加上注解
public class StringToLocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter.format(formatter)); // 将 LocalDateTime 格式化为字符串
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
String dateStr = rs.getString(columnName);
return (dateStr != null) ? LocalDateTime.parse(dateStr, formatter) : null; // 字符串转 LocalDateTime
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String dateStr = rs.getString(columnIndex);
return (dateStr != null) ? LocalDateTime.parse(dateStr, formatter) : null;
}
@Override
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String dateStr = cs.getString(columnIndex);
return (dateStr != null) ? LocalDateTime.parse(dateStr, formatter) : null;
}
}


这里需要说明的事情是,需要在实体类上面标注

这是因为,我们点击查看typeHandler属性的说明

三、后记
面对数据库字段类型和实际设计不符合,但是由于历史问题不能改动表结构的情况下,编写适配器是合适的方式。我们在java代码层面依然像往常一下操作即可,这也提醒我们要如何进行版本兼容。

浙公网安备 33010602011771号