擴展MyBatisPlus默認分頁查詢返回自定義對象

一、背景

mybatisPlus默認BaseMapper的分頁查詢方法返回的是PO對象,如果需要返回前端DTO或者VO類還需要在做一層轉換,非常麻煩

二、環境

<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.2.0</version>
	<exclusions>
		<exclusion>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
		</exclusion>
	</exclusions>
</dependency>

三、注入自定義sql

因爲只需要改造selectPage方法的返回值,那直接CV就好

  1. sql模板
public class SelectByPage extends AbstractMethod {

    /**
     * mapper 對應的方法名
     */
    private static final String MAPPER_METHOD = "selectByPage";

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        SqlMethod sqlMethod = SqlMethod.SELECT_PAGE;
        String sql = String.format(sqlMethod.getSql(), sqlSelectColumns(tableInfo, true),
                tableInfo.getTableName(), sqlWhereEntityWrapper(true, tableInfo),
                sqlComment());
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addSelectMappedStatementForTable(mapperClass, MAPPER_METHOD, sqlSource, tableInfo);
    }
}

  1. 注入sql
public class CustomerSqlInjector extends DefaultSqlInjector {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
        methodList.add(new SelectByPage());
        return methodList;
    }
}
  1. 通用mapper
public interface CommonMapper<T> extends BaseMapper<T> {

    <E> IPage<E> selectByPage(IPage<E> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

}
  1. 通用Service
public class CommonServiceImpl<M extends CommonMapper<T>, T> extends ServiceImpl<M, T> {

    public <E> IPage<E> selectByPage(IPage<E> page, Wrapper<T> wrapper) {
        return baseMapper.selectByPage(page, wrapper);
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章