mybatis-plus 前端优雅传参进行排序
痛点
前端页面列表,往往有排序需求,需要传递排序参数给后端,由后端根据参数进行排序,但现有mybatis-plus的分页插件仅支持传递column,为了一个分页参数,还需要单独给前端说传递的表格中列名,就非常不优雅,能不能传递类字段名称呢?
解决方案:自定义分页插件
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.OrderByElement;
public class MyPageInterceptor extends PaginationInnerInterceptor{
@Override
protected List<OrderByElement> addOrderByElements(List<OrderItem> orderList, List<OrderByElement> orderByElements) {
orderByElements = CollectionUtils.isEmpty(orderByElements) ? new ArrayList<>(orderList.size()) : orderByElements;
List<OrderByElement> orderByElementList = orderList.stream()
.filter(item -> StringUtils.isNotBlank(item.getColumn()))
.map(item -> {
OrderByElement element = new OrderByElement();
element.setExpression(new Column(camelToUnderscore(item.getColumn())));
element.setAsc(item.isAsc());
element.setAscDescPresent(true);
return element;
}).collect(Collectors.toList());
orderByElements.addAll(orderByElementList);
return orderByElements;
}
public MyPageInterceptor(DbType dbType){
super(dbType);
}
public static String camelToUnderscore(String camelCaseStr) {
if (camelCaseStr == null || camelCaseStr.isEmpty()) {
return camelCaseStr;
}
StringBuilder result = new StringBuilder();
int length = camelCaseStr.length();
for (int i = 0; i < length; i++) {
char ch = camelCaseStr.charAt(i);
if (Character.isUpperCase(ch)) {
// 在大写字母前添加下划线,并将大写字母转换为小写
if (i != 0) {
result.append('_');
}
result.append(Character.toLowerCase(ch));
} else {
result.append(ch);
}
}
return result.toString();
}
}
把自定义插件加入拦截器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.annotation.DbType;
@Configuration
public class MybatisPlusConfig {
// 最新版分页插件
@Bean
MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new MyPageInterceptor(DbType.SQL_SERVER2005));
return interceptor;
}
}
思路
首先继承原来分页插件,覆写原分页插件中的addOrderByElements
方法,主要就是对传递进来的column
进行camelToUnderscore
(驼峰转下划线)处理,这样前端传递类字段
即可,传递过来后,由camelToUnderscore
把传过来的名称转为下划线格式。这样前端可以任意使用字段进行排序
注意
使用该方式排序需要满足以下条件:
- 数据库忽略大小写;
- 数据库字段命名使用下滑线;