Mybatis映射LocalDateTime或LocalDate类型为NULL时报错
自定义类型转换器
LocalDateTime
@Component
@MappedJdbcTypes({JdbcType.TIMESTAMP, JdbcType.DATE, JdbcType.TIME})
@MappedTypes(LocalDateTime.class)
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {
@Override
public LocalDateTime getResult(ResultSet rs, String columnName) throws SQLException {
Object object = rs.getObject(columnName);
if(object==null){
return null;
}
return super.getResult(rs, columnName);
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType)
throws SQLException {
ps.setObject(i, parameter);
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getObject(columnName, LocalDateTime.class);
}
@Override
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getObject(columnIndex, LocalDateTime.class);
}
@Override
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getObject(columnIndex, LocalDateTime.class);
}
}
LocalDate
@Component
@MappedJdbcTypes({JdbcType.TIMESTAMP, JdbcType.DATE, JdbcType.TIME})
@MappedTypes(LocalDate.class)
public class LocalDateTypeHandler extends BaseTypeHandler<LocalDate> {
@Override
public LocalDate getResult(ResultSet rs, String columnName) throws SQLException {
Object object = rs.getObject(columnName);
if (object == null) {
return null;
}
return super.getResult(rs, columnName);
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalDate parameter, JdbcType jdbcType)
throws SQLException {
ps.setObject(i, parameter);
}
@Override
public LocalDate getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getObject(columnName, LocalDate.class);
}
@Override
public LocalDate getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getObject(columnIndex, LocalDate.class);
}
@Override
public LocalDate getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getObject(columnIndex, LocalDate.class);
}
}
添加Mybatis配置,注册这两个类型处理器
mybatis
type-handlers-package: xxxx.config.mybatis #这里写你的处理器的bao路径
版权声明:本文为lq6812574原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。