项目需要,把以前分页模板拿出来,改改了,可支持原生的sql进行分页
- MybatisPageServiceTemplate分页模板类
package com.key.win.base.page;
import com.baomidou.mybatisplus.core.conditions.AbstractWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.OrderBySegmentList;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.key.win.base.auth.AuthenticationUtil;
import com.key.win.base.mapper.KeyWinMapper;
import com.key.win.base.util.SingleSoldierConstantUtils;
import com.key.win.base.web.CodeEnum;
import com.key.win.base.web.OrderDir;
import com.key.win.base.web.PageRequest;
import com.key.win.base.web.PageResult;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public abstract class MybatisPageServiceTemplate<T, RT> {
private static final Logger logger = LoggerFactory.getLogger(MybatisPageServiceTemplate.class);
private final BaseMapper baseMapper;
public MybatisPageServiceTemplate(BaseMapper baseMapper) {
super();
this.baseMapper = baseMapper;
}
public PageResult<RT> doPagingQuery(PageRequest<T> pageParam) {
logger.info("进行分页参数组装");
Page<RT> page = new Page<RT>();
page.setCurrent(pageParam.getPageNo());
page.setSize(pageParam.getPageSize());
logger.info("分页查询条件构建");
AbstractWrapper wrapper = this.constructWrapper(pageParam.getT());
this.constructOrderByCondition(pageParam, wrapper);
logger.info("执行分页查询");
IPage<RT> pages = selectPage(page, wrapper);
logger.info("执行分页查询结果组装");
PageResult<RT> pageResult = new PageResult<RT>();
pageResult.setCount(pages.getTotal());
pageResult.setPageNo(pageParam.getPageNo());
pageResult.setPageSize(pageParam.getPageSize());
pageResult.setData(page.getRecords());
pageResult.setCode(CodeEnum.SUCCESS.getCode());
logger.info("执行分页查询结果组装完成,返回PageResult");
return pageResult;
}
protected String constructNativeSql() {
return null;
}
protected boolean isNativeSql() {
if (StringUtils.isNotBlank(this.constructNativeSql())) {
return true;
}
return false;
}
private IPage<RT> selectPage(Page<RT> page, AbstractWrapper wrapper) {
if (this.isNativeSql()) {
KeyWinMapper<RT> keyWinMapper = (KeyWinMapper) baseMapper;
QueryWrapper<RT> queryWrapper = (QueryWrapper) wrapper;
return keyWinMapper.selectPageForNativeSql(page, this.constructNativeSql(), queryWrapper);
} else {
return baseMapper.selectPage(page, wrapper);
}
}
private void constructOrderByCondition(PageRequest<T> pageParam, AbstractWrapper wrapper) {
TableInfo tableInfo = getTableInfo(pageParam);
if (tableInfo == null) {
logger.warn("没有找到数据库表结构,不进行排序操作!");
return;
}
appendSqlOrderByCondition(pageParam, wrapper, tableInfo);
}
private void appendSqlOrderByCondition(PageRequest<T> pageParam, AbstractWrapper wrapper, TableInfo tableInfo) {
List<MybatisOderByVo> orderList = getOrderByCondition(pageParam);
StringBuilder subSqlOrderBy = new StringBuilder();
Map<String, TableFieldInfo> propertyToTableFieldInfoMap = tableInfo.getFieldList().stream().collect(Collectors.toMap(TableFieldInfo::getProperty, a -> a, (k1, k2) -> k1));
for (int i = 0; i < orderList.size(); i++) {
MybatisOderByVo ob = orderList.get(i);
String column = propertyToTableFieldInfoMap.get(ob.getSortName()).getColumn();
if (StringUtils.isNotBlank(column)) {
subSqlOrderBy.append(SingleSoldierConstantUtils.SQL_SEPARATOR).append(column).append(SingleSoldierConstantUtils.SQL_SEPARATOR).append(ob.getSortDir().name());
} else {
logger.warn("{}在propertyToTableFieldInfoMap中找不到映射字段!", ob.getSortName());
}
if (i < orderList.size() - 1 && subSqlOrderBy.length() > 0) {
subSqlOrderBy.append(SingleSoldierConstantUtils.SQL_COMMA_SEPARATOR);
}
}
if (subSqlOrderBy.length() > 0) {
StringBuilder sqlOrderBy = getSqlOrderBy(wrapper);
sqlOrderBy.append(subSqlOrderBy);
wrapper.last(sqlOrderBy.toString());
logger.info("分页查询排序条件:{}", sqlOrderBy.toString());
} else {
logger.warn("最终在propertyToTableFieldInfoMap中找不到一个映射字段,本次分页查询将放弃排序!");
}
}
private StringBuilder getSqlOrderBy(AbstractWrapper wrapper) {
OrderBySegmentList orderBySegmentList = wrapper.getExpression().getOrderBy();
StringBuilder sqlOrderBy = new StringBuilder();
if (CollectionUtils.isEmpty(orderBySegmentList)) {
sqlOrderBy.append(SingleSoldierConstantUtils.ORDER_BY);
logger.info("执行sql中没有order by条件,将为此sql添加order by条件");
} else {
sqlOrderBy.append(SingleSoldierConstantUtils.SQL_COMMA_SEPARATOR);
logger.info("执行sql中已有order by条件,将直接为此sql添加具体排序语句。");
}
return sqlOrderBy;
}
private List<MybatisOderByVo> getOrderByCondition(PageRequest<T> pageParam) {
List<MybatisOderByVo> orderList = new ArrayList();
List<MybatisOderByVo> queryOrder = this.getQueryOrder(pageParam);
if (queryOrder != null && queryOrder.size() > 0) {
orderList.addAll(queryOrder);
logger.info("执行自定义分页排序条件");
} else {
if (StringUtils.isNotBlank(pageParam.getSortName())) {
orderList.add(new MybatisOderByVo(pageParam.getSortName(), pageParam.getSortDir()));
logger.info("执行用户传入的分页条件{}->{}", pageParam.getSortName(), pageParam.getSortDir());
} else {
if (!this.isNativeSql()) {
orderList.add(new MybatisOderByVo(SingleSoldierConstantUtils.QUERY_DEFAULT_ORDER_NAME, OrderDir.DESC));
logger.info("执行默认分页排序条件");
} else {
logger.info("原生sql,不添加默认分页排序条件");
}
}
}
return orderList;
}
private TableInfo getTableInfo(PageRequest<T> pageParam) {
TableInfo tableInfo = null;
if (pageParam.getT() != null) {
tableInfo = TableInfoHelper.getTableInfo(pageParam.getT().getClass());
logger.info("{}用户查询分页时提交了对应的Model对象:{}", AuthenticationUtil.getUserName(), pageParam.getT().getClass());
}
if (tableInfo == null) {
List<TableInfo> tableInfos = TableInfoHelper.getTableInfos();
if (CollectionUtils.isNotEmpty(tableInfos)) {
tableInfo = tableInfos.get(0);
logger.info("tableInfos的大小为{}个,获取第0个TableInfo的名称:{}", tableInfos.size(), tableInfo.getTableName());
}
}
return tableInfo;
}
abstract protected AbstractWrapper constructWrapper(T t);
protected List<MybatisOderByVo> getQueryOrder(PageRequest<T> pageParam) {
return null;
}
}
package com.key.win.base.page;
import com.key.win.base.web.OrderDir;
import io.swagger.annotations.ApiModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@ApiModel("Mybatis排序VO")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MybatisOderByVo implements Serializable {
private String sortName;
private OrderDir sortDir;
}
- 如果要原生sql进行分页,对应的mapper需要继承KeyWinMapper
package com.key.win.base.mapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.ArrayList;
public interface KeyWinMapper<T> extends BaseMapper<T> {
@Select({"${sql} ${ew.customSqlSegment}"})
IPage<T> selectPageForNativeSql(IPage<T> page, @Param("sql") String sql, @Param("ew") QueryWrapper<T> queryWrapper);
@Select({"${sql} ${ew.customSqlSegment}"})
ArrayList<T> selectListForNativeSql(@Param("sql") String sql, @Param("ew") QueryWrapper<T> queryWrapper);
}
- 分页的模板的使用
- 使用LambdaQueryWrapper来构建查询分页
public PageResult<MybatiesTemplate> findMybatiesTemplateByPaged(PageRequest<MybatiesTemplate> pageRequest) {
MybatisPageServiceTemplate<MybatiesTemplate, MybatiesTemplate> page = new MybatisPageServiceTemplate<MybatiesTemplate, MybatiesTemplate>(this.baseMapper) {
@Override
protected AbstractWrapper constructWrapper(MybatiesTemplate mybatiesTemplate) {
LambdaQueryWrapper<MybatiesTemplate> lqw = new LambdaQueryWrapper<MybatiesTemplate>();
if (mybatiesTemplate != null && StringUtils.isNotBlank(mybatiesTemplate.getName())) {
lqw.like(MybatiesTemplate::getName, mybatiesTemplate.getName() == null ? "" : mybatiesTemplate.getName());
}
if (mybatiesTemplate != null && StringUtils.isNotBlank(mybatiesTemplate.getCode())) {
lqw.like(MybatiesTemplate::getCode, mybatiesTemplate.getCode() == null ? "" : mybatiesTemplate.getCode().toUpperCase());
}
lqw.orderByDesc(MybatiesTemplate::getCreateDate);
return lqw;
}
};
return page.doPagingQuery(pageRequest);
}
public PageResult<UserOrganVo> getUserOrganByPaged(PageRequest<UserOrganVo> pageRequest) {
MybatisPageServiceTemplate<UserOrganVo, UserOrganVo> query = new MybatisPageServiceTemplate<UserOrganVo, UserOrganVo>(mybatiesSqlTemplateDao) {
@Override
protected AbstractWrapper constructWrapper(UserOrganVo userOrganVo) {
QueryWrapper<UserOrganVo> queryWrapper = new QueryWrapper<UserOrganVo>();
if (userOrganVo != null) {
if (StringUtils.isNotBlank(userOrganVo.getUserName())) {
queryWrapper.eq("u.user_name", userOrganVo.getUserName());
}
if (StringUtils.isNotBlank(userOrganVo.getOrganName())) {
queryWrapper.eq("o.name", userOrganVo.getOrganName());
}
}
return queryWrapper;
}
@Override
protected String constructNativeSql() {
return "SELECT u.user_name ,o.`name` as organ_name FROM sys_user u INNER JOIN sys_user_organ uo on u.id = uo.user_id INNER JOIN sys_organ o on uo.organ_id = o.id";
}
};
return query.doPagingQuery(pageRequest);
}
|