项目中遇到要对数据库加密,简单的方法是在构建实体类时调用加密算法加密后,调用insert插入数据库,但这样做比较繁琐,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 DBInterceptor implements Interceptor{
private final Logger logger = LoggerFactory.getLogger(DBInterceptor.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
String methodName = invocation.getMethod().getName();
Object parameter = invocation.getArgs()[1];
BoundSql sql = statement.getBoundSql(parameter);
logger.info("sql is {}",sql.getSql());
if(parameter instanceof SystemUser){
SystemUser user = (SystemUser)parameter;
if(methodName.equals("query")){
}else if(methodName.equals("update")){
user.setName(DBSecurityUtil.getInstance().encrypt(user.getName()));
user.setPassword(Digests.md5(user.getPassword().getBytes()));
}
}
Object returnValue = invocation.proceed();
if(returnValue instanceof ArrayList<?>){
List<?> list = (ArrayList<?>)returnValue;
for(Object val:list){
if(val instanceof SystemUser){
SystemUser user = (SystemUser)val;
logger.debug("user name is {}",user.getName());
user.setName(DBSecurityUtil.getInstance().decrypt(user.getName()));
logger.debug("user name is {}",user.getName());
}
}
}
return returnValue;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub
}
}
spring 配置如下:
<!-- MyBatis配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="typeAliasesPackage" value="com.xxxx.entity" />
<!-- 显式指定Mapper文件位置 -->
<property name="mapperLocations" value="classpath:/com/xxx/repository/mybatis/mapper/*Mapper.xml" />
<!-- 配置Mybatis的插件plugin-->
<property name="plugins">
<array>
<bean class="com.xxxx.utils.security.DBInterceptor">
<property name="properties">
<value>
property-key=property-value
</value>
</property>
</bean>
</array>
</property>
</bean>