当前位置: 首页>后端>正文

BaseTypeHandler实现数据库查询字段转换

场景:想将数据查询出的-1统一转化成null
解决: 通过mybatis的BaseTypeHandler实现特殊字段映射
以long类型为例,其他类型同理

@Component
public class LongHandler extends BaseTypeHandler<Long> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Long number, JdbcType jdbcType) throws SQLException {
        preparedStatement.setLong(i, number);
    }

    @Override
    public Long getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        Long value = resultSet.getLong(columnName);
        if (value == -1) {
            return null;
        }
        return value;
    }

    @Override
    public Long getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        Long value = resultSet.getLong(columnIndex);
        if (value == -1) {
            return null;
        }
        return value;
    }

    @Override
    public Long getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        Long value = callableStatement.getLong(columnIndex);
        if (value == -1) {
            return null;
        }
        return value;
    }

参考链接:
1、MyBatis借助BaseTypeHandler实现特殊的字段(数组或json)映射


https://www.xamrdz.com/backend/3u51931841.html

相关文章: