最近考虑myBatis中sql语句使用规范的问题,如果漏下条件或者写一些不规范语句会对程序性能造成很大影响。最好的方法就是利用代码进行限制,通过拦截器进行sql格式的判断在自测环节就能找到问题。写了个简单情景下的demo,并通过idea插件来将myBatis的mapper方法都打上拦截器判断的注解,多少自动化一点。
需求简介
使用myBatis拦截器对Mapper的sql进行判断,对增加了自定义注解修饰的方法进行where条件的判断,存在where子句再执行,否则抛出异常。
具体实现
自定义注解
// 标志注解,用来表示mapper方法需要经过where条件存在与否的判断
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface WhereConditionCheck {
}
限定method修饰,同时指定runtime,以在运行过程中判断是否被该注解修饰。
拦截器实现类
WhereConditionInterceptor拦截器判断类
@Intercepts({
// 拦截query方法
@Signature(type = Executor.class, method = "query",
args = {
MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class,method = "update",args = {
MappedStatement.class, Object.class})
})
@Component
@Slf4j
// 利用myBatis拦截器去获取对应的语句,where条件放行,无where阻止
public class WhereConditionInterceptor implements Interceptor {
首先利用@Intercepters注解,定义拦截器拦截的方法。这些方法来自Mybatis执行时调用的Executor接口的实现类,并通过args参数的设置来唯一指定同名的重载方法。
@Override
public Object intercept(Invocation invocation) throws Throwable