用户提交的数据信息,要去掉字符串前后面的空格,即TRIM,绝大多数企业应用都需要。
一个一个改?
太麻烦了!
用户输入条件查询数据,同样要去掉空格,否则可能导致查不出来数据。并且,通常,我们在排查这样的问题的时候,也许只有眼明心细的人,才能发现原来是有空格导致的。
一个一个改?
太麻烦了!
本文使用拦截器(Interceptor)来实现全局处理。mybatis自带Interceptor接口,我们只需实现接口即可。
mybatisplus或mybatis的数据库操作,主要体现在update和query两个方法上,见下面mybatis-**.jar的Executor接口。
我们所需要的拦截的,也是这个接口所定义的CRUD操作方法。
mybatis的拦截器同样定义在mybatis-**.jar中。
查询数据拦截器处理
查询数据拦截Executor.query方法。对于mybatisplus,请求参数一般是lambda表达式,所以我们对lambda表达式携带的数据进行改造。
代码如下:
View Code
插入数据的拦截器处理
插入数据\修改数据统一拦截Executor.update方法。请求参数一般是pojo对象,利用反射来修改属性的值。
代码如下:
@Slf4j
@Component
@Intercepts({@Signature(type= Executor.class, method = "update", args = {MappedStatement.class, Object.class})})public class MybatisInterceptor implementsInterceptor {
@Overridepublic Object intercept(Invocation invocation) throwsThrowable {
MappedStatement mappedStatement= (MappedStatement) invocation.getArgs()[0];
String sqlId=mappedStatement.getId();
log.debug("------sqlId------" +sqlId);
SqlCommandType sqlCommandType=mappedStatement.getSqlCommandType();
Object parameter= invocation.getArgs()[1];
log.debug("------sqlCommandType------" +sqlCommandType);if (parameter == null) {returninvocation.proceed();
}if (SqlCommandType.INSERT == sqlCommandType || SqlCommandType.UPDATE ==sqlCommandType) {
Field[] fields=oConvertUtils.getAllFields(parameter);for(Field field : fields) {if (field.getType().equals(String.class)) {
field.setAccessible(true);
Object o=field.get(parameter);
field.setAccessible(false);
String newVal= o == null ? "": String.valueOf(o).trim();
field.setAccessible(true);
field.set(parameter, newVal);
field.setAccessible(false);
}
}
}returninvocation.proceed();
}
}
View Code
测试
下面testcase用来查询数据。同样插入也OK。