敏感欄位(身分證、手機、銀行卡)在資料庫加密存儲,應用層透過 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) {
// 可讀取外部配置
}
}
<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 針對特定參數位置處理