萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MyBatis Interceptor 實作:查詢參數加密與結果解密攔截器

應用場景

敏感欄位(身分證、手機、銀行卡)在資料庫加密存儲,應用層透過 MyBatis 攔截器自動處理參數加密與結果解密,業務代碼無感知。

攔截器完整實作

@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class EncryptInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(EncryptInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        dealParameter(invocation);           // 執行前:參數加密
        Object returnValue = invocation.proceed(); // 執行原查詢/更新
        dealReturnValue(returnValue);        // 執行後:結果解密
        return returnValue;
    }

    // 參數加密處理
    private void dealParameter(Invocation invocation) {
        MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
        String mapperPath = ConfigUtils.get("mybaits.mapper.path");
        String methodName = statement.getId().substring(statement.getId().indexOf(mapperPath) + mapperPath.length() + 1);

        // 僅處理 UserBaseMapper 相關方法
        if (methodName.startsWith("UserBaseMapper")) {
            if (methodName.equals("UserBaseMapper.updateDriver")) {
                ((Driver) invocation.getArgs()[1]).encrypt(); // 呼叫實體類加密方法
            }
        }
        logger.info("Mybatis Encrypt parameters Interceptor, method: {}, args: {}", methodName, invocation.getArgs()[1]);
    }

    // 結果解密處理
    private void dealReturnValue(Object returnValue) {
        if (returnValue instanceof ArrayList) {
            List list = (ArrayList) returnValue;
            for (Object val : list) {
                if (val instanceof Passenger) {
                    // TODO: 實作解密邏輯 val.decrypt()
                }
                logger.info("Mybatis Decrypt result Interceptor, result object: {}", ToStringBuilder.reflectionToString(val));
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可讀取外部配置
    }
}

Spring 整合配置

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="typeAliasesPackage" value="com.xx.model"/>
    <property name="dataSource" ref="dataSource"/>
    <property name="mapperLocations" value="classpath*:mybatis/*.xml"/>
    <property name="plugins">
        <array>
            <bean class="com.github.pagehelper.PageHelper">
                <property name="properties">
                    <value>dialect=hsqldb</value>
                </property>
            </bean>
            <bean class="com.xx.interceptor.EncryptInterceptor">
                <property name="properties">
                    <value>property-key=property-value</value>
                </property>
            </bean>
        </array>
    </property>
</bean>

關鍵設計點

設計點說明
攔截點Executor.update/query 覆蓋增刪改查
方法識別解析 MappedStatement.getId() 判斷目標 Mapper/方法
加密委派實體類自帶 encrypt()/decrypt(),符合單一職責
類型安全instanceof 判斷後再轉型處理
日誌審計記錄方法名、參數、結果,便於追蹤

擴展建議

  • 使用註解標記敏感欄位(@Encrypted),攔截器通用處理而非硬編碼方法名
  • 支援字段級加密:解析 BoundSql 針對特定參數位置處理
  • 整合金鑰管理系統(KMS、Vault)動態獲取加密金鑰
  • 加入效能監控:記錄加解密耗時,評估對查詢延遲影響
  • 考慮讀寫分離場景:從庫查詢是否需要解密
copyright © 萬盛學電腦網 all rights reserved