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

mybatis的使用BaseTypeHandler实现参数重写(入库前加解密、JSON序列化与反序列化)

1、入库加解密

配置方式:

@Slf4j
public class SensitiveHandler extends BaseTypeHandler<String> {
@Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType)
            throws SQLException {
        // 加密
        preparedStatement.setString(i, encrypt(s));
    }

    @Override
    public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return tryDecrypt(resultSet.getString(s));
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return tryDecrypt(resultSet.getString(i));
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return tryDecrypt(callableStatement.getString(i));
    }
    //加密
    private String encrypt(String data) {
    }
    //解密:解密失败后,返回data
   private String tryDecrypt(String data) {
   }
}

使用方式:

@Data
@EqualsAndHashCode(callSuper = false)
@Builder
@TableName("t_test", autoResultMap = true)
public class Test extends Model<Test> {
    /**
     * 自增id
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 地址
     */
    @TableField(typeHandler = KeyCenterHandler.class)
    private String address;
}

2、JSON序列化与反序列化

public abstract class AbstractJsonArrayTypeHandler<E> extends BaseTypeHandler<List<E>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<E> e, JdbcType jdbcType)
            throws SQLException {
        preparedStatement.setString(i, ObjectMapperUtils.toJSON(e));
    }

    @Override
    public List<E> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return fromJSON(resultSet.getString(s));
    }

    @Override
    public List<E> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return fromJSON(resultSet.getString(i));
    }

    @Override
    public List<E> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return fromJSON(callableStatement.getString(i));
    }

    protected List<E> fromJSON(String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return ObjectMapperUtils.fromJSON(value, List.class, getFromJsonClass());
    }

    protected abstract Class<E> getFromJsonClass();
}

工具类:ObjectMapperUtils.fromJSON

MAPPER.readValue(json,
                    defaultInstance().constructCollectionType(collectionType, valueType));

子类:每多一种对象,都要新增一个解析器:

public class JsonArrayStringTypeHandler extends AbstractJsonArrayTypeHandler<String> {
    @Override
    protected Class<String> getFromJsonClass() {
        return String.class;
    }
}

注意事项

注意事项:mybatisPlus如果使用wrapper来更新字段时,那么不会生效。更新保存与查询必须以对象为维度。


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

相关文章: