通过mybatis-plus进行数据库字段加解密

目录

1、编写handler

2、编写加解密util

3、实体及字段配置

4、自定义mapper语句


1、编写handler

@MappedJdbcTypes(JdbcType.VARCHAR)
public class EncryptHandler extends BaseTypeHandler {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String parameter, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, EncryptFieldUtil.encrypt(parameter));
    }

    @Override
    public String getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return EncryptFieldUtil.decrypt(resultSet.getString(columnName));
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return EncryptFieldUtil.decrypt(resultSet.getString(columnIndex));
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return EncryptFieldUtil.decrypt(callableStatement.getString(columnIndex));
    }

}

2、编写加解密util

public class EncryptFieldUtil {
    /**
     * 数据库字段加密key
     */
    private static final byte[] KEY = "sdfdfsdfdfghhhss".getBytes(StandardCharsets.UTF_8);

    /**
     * 加密字段
     */
    public static String encrypt(String value) {
        if (StrUtil.isBlank(value)) {
            return value;
        }
        AES aes = SecureUtil.aes(KEY);
        return aes.encryptHex(value);
    }

    /**
     * 解密字段
     */
    public static String decrypt(String value) {
        if (null == value) {
            return null;
        }
        try {
            return SecureUtil.aes(KEY).decryptStr(value);
        } catch (CryptoException e) {
            return value;
        }
    }

}

3、实体及字段配置

@TableName(value = "表名", autoResultMap = true)

@TableField(typeHandler = EncryptHandler.class)

4、自定义mapper语句

 
       
 

你可能感兴趣的:(架构,mybatis,数据库,java)