在项目中,会出现一些对sql处理的需求,如果sql *** 作很多,为了简化处理,可以在sql执行的时候加入一个拦截器,并对将要执行的sql进行统一的处理。
这里已使用了mybatisplus客户端为例的实现方式。
代码实现 maven引入依赖jar,数据库配置就不写这了。
com.baomidou
mybatis-plus-boot-starter
3.4.3
com.alibaba
druid-spring-boot-starter
1.2.5
mysql
mysql-connector-java
runtime
自定义拦截器
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.util.TablesNamesFinder;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
@Slf4j
public class LizzMybatisIntercepts implements InnerInterceptor {
@Override
public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
log.info("#####willDoQuery");
return false;
}
@Override
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
log.info("#####beforeQuery");
}
@Override
public boolean willDoUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
log.info("#####willDoUpdate");
// 一堆sql处理仅供参考
BoundSql boundSql = ms.getBoundSql(parameter);
ms.getSqlSource().getClass();
String sql = boundSql.getSql();
Statement statement = null;
try {
statement = CCJSqlParserUtil.parse(sql);
} catch (JSQLParserException e) {
e.printStackTrace();
}
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
List tableList = tablesNamesFinder.getTableList(statement);
log.info("sql:{}",sql);
return false;
}
@Override
public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
log.info("#####beforeUpdate");
}
@Override
public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
log.info("#####beforePrepare");
}
@Override
public void beforeGetBoundSql(StatementHandler sh) {
log.info("#####beforeGetBoundSql");
}
@Override
public void setProperties(Properties properties) {
log.info("#####setProperties");
}
}
增加拦截器
@Configuration
public class CipherMybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 自定义拦截器,先添加先执行。
interceptor.addInnerInterceptor(new LizzMybatisIntercepts());
// 自带分页拦截器
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)