>  기사  >  Java  >  SpringBoot MP 단순 페이징 쿼리 테스트 구현 방법

SpringBoot MP 단순 페이징 쿼리 테스트 구현 방법

王林
王林앞으로
2023-05-16 16:43:251095검색

최신 mp 종속성을 가져오는 것이 첫 번째 단계입니다. 그렇지 않으면 너무 낮은 버전에서는 아무것도 수행할 수 없습니다. 3 및 1 미만 버전의 페이징 플러그인도 추가되지 않은 것 같아서 최신 3.5를 사용하여 보장합니다. 모든 것이 포함되어 있습니다:

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>

여기서는 mp의 핵심 플러그인인 MybatisPlusInterceptor와 자동 페이징 플러그인인 PaginationInnerInterceptor라는 두 가지 플러그인을 알아야 합니다.

MybatisPlusInterceptor의 소스 코드(중간 처리 코드 제거):

public class MybatisPlusInterceptor implements Interceptor {
    private List<InnerInterceptor> interceptors = new ArrayList();
    public MybatisPlusInterceptor() {}
    public Object intercept(Invocation invocation) throws Throwable {}
    public Object plugin(Object target) {}
    public void addInnerInterceptor(InnerInterceptor innerInterceptor) {}
    public List<InnerInterceptor> getInterceptors() {}
    public void setProperties(Properties properties) {}
    public void setInterceptors(final List<InnerInterceptor> interceptors) {}
}

개인 속성 목록 List가 있고 이 연결 목록의 요소 유형이 InnerInterceptor임을 알 수 있습니다.

InnerInterceptor 소스 코드:

public interface InnerInterceptor {
    default boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        return true;
    }
    default void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    }
    default boolean willDoUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        return true;
    }
    default void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
    }
    default void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
    }
    default void beforeGetBoundSql(StatementHandler sh) {
    }
    default void setProperties(Properties properties) {
    }
}

이 인터페이스의 내용은 대략적으로 기본 속성을 설정하는 내용임을 쉽게 알 수 있습니다. 코드의 의미로 보면 기본 데이터베이스 작업 전후에 실행될 몇 가지 논리를 제공합니다. 실행 기간. 해당 메소드를 구현하는 사람은 누구나 새로운 기능을 얻게 됩니까?

PaginationInnerInterceptor 플러그인의 소스 코드를 살펴보세요.

public class PaginationInnerInterceptor implements InnerInterceptor {
    protected static final List<SelectItem> COUNT_SELECT_ITEM = Collections.singletonList((new SelectExpressionItem((new Column()).withColumnName("COUNT(*)"))).withAlias(new Alias("total")));
    protected static final Map<String, MappedStatement> countMsCache = new ConcurrentHashMap();
    protected final Log logger = LogFactory.getLog(this.getClass());
    protected boolean overflow;
    protected Long maxLimit;
    private DbType dbType;
    private IDialect dialect;
    protected boolean optimizeJoin = true;
    public PaginationInnerInterceptor(DbType dbType) {
        this.dbType = dbType;
    }
    public PaginationInnerInterceptor(IDialect dialect) {
        this.dialect = dialect;
    }
    public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        IPage<?> page = (IPage)ParameterUtils.findPage(parameter).orElse((Object)null);
        if (page != null && page.getSize() >= 0L && page.searchCount()) {
            MappedStatement countMs = this.buildCountMappedStatement(ms, page.countId());
            BoundSql countSql;
            if (countMs != null) {
                countSql = countMs.getBoundSql(parameter);
            } else {
                countMs = this.buildAutoCountMappedStatement(ms);
                String countSqlStr = this.autoCountSql(page, boundSql.getSql());
                MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
                countSql = new BoundSql(countMs.getConfiguration(), countSqlStr, mpBoundSql.parameterMappings(), parameter);
                PluginUtils.setAdditionalParameter(countSql, mpBoundSql.additionalParameters());
            }
            CacheKey cacheKey = executor.createCacheKey(countMs, parameter, rowBounds, countSql);
            List<Object> result = executor.query(countMs, parameter, rowBounds, resultHandler, cacheKey, countSql);
            long total = 0L;
            if (CollectionUtils.isNotEmpty(result)) {
                Object o = result.get(0);
                if (o != null) {
                    total = Long.parseLong(o.toString());
                }
            }
            page.setTotal(total);
            return this.continuePage(page);
        } else {
            return true;
        }
    }
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {...........省略之后全部的内容........}

이 메서드는 InnerInterceptor 인터페이스의 메서드를 구현한다는 것을 쉽게 찾을 수 있으므로 소스 코드를 검토하여 논리를 명확히 해야 합니다.

우리는 페이징 플러그인과 코어 플러그인 사이의 관계를 알고 있습니다. 즉, 페이징 플러그인을 코어 플러그인 내부의 플러그인 연결 목록에 추가하여 다중 플러그인 사용을 실현할 수 있습니다. 기능적인 플러그인.

mp 플러그인을 구성하고 플러그인을 스프링 관리에 넘겨줍니다(우리는 테스트에 springboot를 사용하므로 xml 파일을 사용할 필요가 없습니다):

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MpConfig {
    /*分页插件的配置*/
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        /*创建mp拦截器*/
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        /*创建分页插件*/
        PaginationInnerInterceptor pagInterceptor = new PaginationInnerInterceptor();
        /*设置请求的页面大于最大页容量后的请求操作,true回调第一页,false继续翻页,默认翻页*/
        pagInterceptor.setOverflow(false);
        /*设置单页分页的条数限制*/
        pagInterceptor.setMaxLimit(500L);
        /*设置数据库类型*/
        pagInterceptor.setDbType(DbType.MYSQL);
        /*将分页拦截器添加到mp拦截器中*/
        interceptor.addInnerInterceptor(pagInterceptor);
        return interceptor;
    }
}

구성 후 Mapper 인터페이스 작성:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hlc.mp.entity.Product;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ProductMapper extends BaseMapper<Product> {
}

Create 인터페이스에 대한 서비스 클래스(mp 코딩 스타일을 따라야 함):

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlc.mp.entity.Product;
import com.hlc.mp.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service(value = "ProductService")
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
        implements IService<Product> {
    @Autowired
    ProductMapper productMapper;
    /**
     * 根据传入的页码进行翻页
     *
     * @param current 当前页码(已经约定每页数据量是1条)
     * @return 分页对象
     */
    public Page<Product> page(Long current) {
        /*current首页位置,写1就是第一页,没有0页之说,size每页显示的数据量*/
        Page<Product> productPage = new Page<>(current, 1);
        /*条件查询分页*/
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        productMapper.selectPage(productPage, queryWrapper);
        return productPage;
    }
}

여기서 구체적인 페이징 방법은 먼저 페이징 개체를 생성하고, 페이지 번호와 각 페이지의 데이터 양을 지정하고, 그런 다음 쿼리 작업의 범위를 결정하고 BaseMapper에서 제공한 쿼리 페이징 메서드 selectPage(E 페이지, Wapper queryWapper)를 사용하여 쿼리 페이징 작업을 수행합니다.

테스트 클래스:

    @Test
    public void testPage(){
        IPage<Product> productIPage = productService.page(2L);
        productIPage.getRecords().forEach(System.out::println);
        System.out.println("当前页码"+productIPage.getCurrent());
        System.out.println("每页显示数量"+productIPage.getSize());
        System.out.println("总页数"+productIPage.getPages());
        System.out.println("数据总量"+productIPage.getTotal());
    }

페이징 결과 보기 실행:

SpringBoot MP 단순 페이징 쿼리 테스트 구현 방법

각 페이지마다 한 부분만 표시하도록 설정했기 때문에 전달한 페이지 번호에 따라 해당 페이지 데이터가 정상적으로 쿼리되는 것을 확인할 수 있습니다. 따라서 ID가 페이지 번호와 일치하면 페이징이 성공한 것입니다.

위 내용은 SpringBoot MP 단순 페이징 쿼리 테스트 구현 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제