Mybatis-Plus通过全局拦截实现查询SQL根据创建时间排序(create_time)
①自定义SQL拦截器(通过重写processSelect方法,对select进行拦截,并构建添加规则)
/**
* 自定义SQL拦截器
* @author xsong
*/
@Slf4j
@Component
public class CustomSQLInterceptor extends JsqlParserSupport implements InnerInterceptor {
@Override
public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
// 这里固定这么写就可以了
PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
MappedStatement ms = mpSh.mappedStatement();
if (InterceptorIgnoreHelper.willIgnoreTenantLine(ms.getId())) {
return;
}
PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();
mpBs.sql(parserMulti(mpBs.sql(), null));
}
/**
* 查询操作拦截
* 该方法由JsqlParserSupport提供,主要用于通过API的方式操作SQL
* 思路:通过API构建出新的条件,并将新的条件和之前的条件拼接在一起
*/
@Override
protected void processSelect(Select select, int index, String sql, Object obj) {
// 解析SQL
PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
// 构建排序规则
OrderByElement orderByElement = new OrderByElement();
// 设置为从大到小(降序)
orderByElement.setAsc(false);
// 设置排序字段
orderByElement.setExpression(new Column("create_time"));
// 重新封装条件
plainSelect.addOrderByElements(orderByElement);
// System.out.println(plainSelect);
}
/**
* 插入操作拦截
*/
@Override
protected void processInsert(Insert insert, int index, String sql, Object obj) {
}
/**
* 更新操作拦截
*/
@Override
protected void processUpdate(Update update, int index, String sql, Object obj) {
}
/**
* 删除操作拦截
*/
@Override
protected void processDelete(Delete delete, int index, String sql, Object obj) {
}
}
②将自定义SQL拦截器添加到MybatisPlus拦截器中
/**
* MyBatisPlus配置类
* @author xsong
*/
@Configuration
public class MyBatisPlusConfig {
/**
* MybatisPlus拦截器
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分页插件拦截器
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
// 自定义SQL拦截器
interceptor.addInnerInterceptor(new CustomSQLInterceptor());
return interceptor;
}
}
③实现效果
参考文章(感谢大佬)
①MyBatis Plus 拦截器实现数据权限控制
②JSqlparser 拼接SQL where条件