批量数据查询,分页是必不可少的。mybatis-plus提供了分页插件,以下为集成分页插件的过程。
@Bean
public MybatisPlusInterceptor paginationInterceptor() {
PaginationInnerInterceptor innerInterceptor=new PaginationInnerInterceptor();
innerInterceptor.setDbType(DbType.MYSQL);
innerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(innerInterceptor);
return interceptor;
}
有时候我们需要对执行的sql进行拦截做一些必要的加工;如做权限范围限制。
这时我们就可以在分页插件中添加自定义拦截器来完成了。
代码如下:
@Bean
public MybatisPlusInterceptor paginationInterceptor() {
MybatisPlusInterceptor interceptor=new MybatisPlusInterceptor();
//添加数据权限插件
//自定义interceptor ;交由MybatisPlusInterceptor 管理
interceptor.addInnerInterceptor(new BinKaiDataPermissionInterceptor());
//添加分页插件
PaginationInnerInterceptor innerInterceptor=new PaginationInnerInterceptor();
innerInterceptor.setDbType(DbType.MYSQL);
innerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(innerInterceptor);
return interceptor;
}
实现mybatis-plus拦截器需要继承集成MyBatistplus 的InnerInterceptor,以下是拦截器代码
public class BinKaiDataPermissionInterceptor extends JsqlParserSupport implements InnerInterceptor {
private Logger log=LoggerFactory.getLogger(BinKaiDataPermissionInterceptor.class);
/**
* 查询之前执行,将执行查询
* @param executor
* @param ms
* @param parameter
* @param rowBounds
* @param resultHandler
* @param boundSql
* @return
* @throws SQLException
*/
public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
/*System.out.println("执行前sql:"+boundSql.getSql());*/
return true;
}
/**
* 查询之前执行 在这里处理sql
* @param executor
* @param ms
* @param parameter
* @param rowBounds
* @param resultHandler
* @param boundSql
* @throws SQLException
*/
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
if(rightsManagement==null){
rightsManagement= SpringContextUtils.getContext().getBean(SysRightsManaement.class);
}
PluginUtils.MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
//拦截 id名称以Privilege结尾查询
if(ms.getId().matches(".+Privilege#34;)) {
String sql=mpBoundSql.sql()+" WHERE 2=2 ";
//获取到parameterType 传入的参数
Map param= (Map) parameter;
//权限验证;加工SQL
String resultSql =" and employee='10012'";
sql=sql+resultSql;
mpBoundSql.sql(sql);
System.out.println("执行前sql@:"+mpBoundSql.sql());
}
}
}