解决Mybatis-Plus操作分页后数据失效问题
业务场景
我们知道在使用PageHelper分页插件时,会对执行PageHelper.startPage(pageNum,pageSize);方法后的第一条查询语句进行分页操作。在开发中总会遇到这样的业务情景,在进行分页查询后,需要对获得的列表数据包装成另一种类型,此时需要对新类型的列表进行分页,然而由于PageInfo
如,我在数据库分页后查询到的类为PageInfo
当我们对list属性进行操作时,会同时导致PageInfo类中的其他属性发生改变,如total等。
解决方法
//从数据库获得的Users分页列表 //当我们打印users时,会发现打印出来的数据除了列表数据还有分页属性 Listusers=this.list(); //操作users获得的需要的列表 List userVos=this.list2(users); //创建User的info类,此时page中的属性已生成 PageInfo userPage=newPageInfo<>(users); //创建UserVo的info类 PageInfo userVoPage=newPageInfo<>(userVos); //将userPage中除看list外的其他属性复制到userVoPage中 PageInfoUtilpageInfoUtil=newPageInfoUtil(); pageInfo=pageInfoUtil.getPageVo(userPage,userVoPage);
pageInfoUtil publicclassPageInfoUtil{ publicPageInfogetPageVo(PageInfopageInfoPo,PageInfopageInfoVo){ pageInfoVo.setTotal(pageInfoPo.getTotal()); pageInfoVo.setEndRow(pageInfoPo.getEndRow()); pageInfoVo.setHasNextPage(pageInfoPo.isHasNextPage()); pageInfoVo.setHasPreviousPage(pageInfoPo.isHasPreviousPage()); pageInfoVo.setIsFirstPage(pageInfoPo.isIsFirstPage()); pageInfoVo.setIsLastPage(pageInfoPo.isIsLastPage()); pageInfoVo.setNavigateFirstPage(pageInfoPo.getNavigateFirstPage()); pageInfoVo.setNavigateLastPage(pageInfoPo.getNavigateLastPage()); pageInfoVo.setNavigatePages(pageInfoPo.getNavigatePages()); pageInfoVo.setNavigatepageNums(pageInfoPo.getNavigatepageNums()); pageInfoVo.setNextPage(pageInfoPo.getNextPage()); pageInfoVo.setPageNum(pageInfoPo.getPageNum()); pageInfoVo.setPages(pageInfoPo.getPages()); pageInfoVo.setPageSize(pageInfoPo.getPageSize()); pageInfoVo.setPrePage(pageInfoPo.getPrePage()); pageInfoVo.setSize(pageInfoPo.getSize()); pageInfoVo.setStartRow(pageInfoPo.getStartRow()); pageInfoVo.setFirstPage(pageInfoPo.getFirstPage()); pageInfoVo.setLastPage(pageInfoPo.getLastPage()); returnpageInfoVo; } }
End
想使用秀一点的方法,结果能力有限,没有成功,只能使用这种笨方法,如果有更好的方法,欢迎各位指导。
补充知识:mybatis-plus分页无效,total=0问题(springmvc)
前言
项目中(springmvc)分页采用mybatis-plus,头一回用,就遇到了如题问题
pom.xml
com.baomidou mybatis-plus 3.2.0
mapper继承了BaseMapper
@Repository publicinterfaceUserMapperextendsBaseMapper{ //这里代码没用,查询采用的BaseMapper中的IPage selectPage(IPage page,@Param("ew")Wrapper queryWrapper); }
service层
@Override publicSysUserVolist(UserQoqo){ QueryWrapperqueryWrapper=newQueryWrapper<>(); queryWrapper.like("name",qo.getKeyword()) .or(). like("code",qo.getKeyword()); Page page=newPage<>(qo.getPageNo(),qo.getPageSize()); IPage userPoIPage=userMapper.selectPage(page,queryWrapper); List records=userPoIPage.getRecords(); longtotal=userPoIPage.getTotal();//总记录数 longpages=userPoIPage.getPages();//查询结果数 longpageNo=userPoIPage.getCurrent();//当前页 longpageSize=userPoIPage.getSize();//每页条数 List userVos=Lists.newArrayList(); for(UserPouserPo:records){ IntegeruserId=userPo.getId(); List roles=userMapper.selectRoles(userId); UserVouserVo=UserVo.builder().code(userPo.getCode()) .name(userPo.getName()) .rolePo(roles) .status(userPo.getStatus()) .build(); userVos.add(userVo); } SysUserVosysUserVo=SysUserVo.builder() .list(userVos) .total(total) .build(); returnsysUserVo; }
结果分页并没有生效,于是添加拦截器
packagecom.cebbank.api.config; importcom.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; importcom.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; importorg.mybatis.spring.annotation.MapperScan; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @MapperScan("com.cebbank.api.mapper") publicclassMybatisPlusConfig{ @Bean publicPaginationInterceptorpaginationInterceptor(){ PaginationInterceptorpaginationInterceptor=newPaginationInterceptor(); //设置请求的页面大于最大页后操作,true调回到首页,false继续请求默认false paginationInterceptor.setOverflow(true); //设置最大单页限制数量,默认500条,-1不受限制 paginationInterceptor.setLimit(100); //开启count的join优化,只针对部分leftjoin paginationInterceptor.setCountSqlParser(newJsqlParserCountOptimize(true)); paginationInterceptor.setDialectType("mysql"); returnpaginationInterceptor; } }
还是没生效
最后找到解决方案,在数据源配置中显式添加分页插件
@Bean publicSqlSessionFactorysqlSessionFactory()throwsException{ MybatisSqlSessionFactoryBeansqlSessionFactoryBean=newMybatisSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource()); MybatisConfigurationconfiguration=newMybatisConfiguration(); configuration.setMapUnderscoreToCamelCase(true); configuration.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class); sqlSessionFactoryBean.setConfiguration(configuration); //sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations()); sqlSessionFactoryBean.setPlugins(newInterceptor[]{newPaginationInterceptor()}); returnsqlSessionFactoryBean.getObject(); }
完整配置
packagecom.cebbank.api.config; importcom.alibaba.druid.pool.DruidDataSource; importcom.baomidou.mybatisplus.core.MybatisConfiguration; importcom.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; importcom.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; importorg.apache.ibatis.plugin.Interceptor; importorg.apache.ibatis.session.SqlSessionFactory; importorg.apache.ibatis.type.EnumOrdinalTypeHandler; importorg.mybatis.spring.annotation.MapperScan; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.context.annotation.EnableAspectJAutoProxy; importorg.springframework.jdbc.datasource.DataSourceTransactionManager; importjavax.sql.DataSource; /** *@authorlinyong *@date2020/7/3016:38 *@description数据源配置 **/ @Configuration @EnableAspectJAutoProxy @MapperScan("com.cebbank.api.mapper") publicclassDBConfig{ @Value("${spring.datasource.url}") privateStringurl; @Value("${spring.datasource.driver-class-name}") privateStringdriverClassName; @Value("${spring.datasource.username}") privateStringusername; @Value("${spring.datasource.password}") privateStringpassword; @Value("${spring.datasource.initialSize:5}") privateIntegerinitialSize; @Value("${spring.datasource.maxActive:50}") privateIntegermaxActive; @Value("${spring.datasource.maxWait:60000}") privateIntegermaxWait; @Value("${spring.datasource.minIdle:5}") privateIntegerminIdle; @Value("${spring.datasource.testWhileIdle:true}") privateBooleantestWhileIdle; @Value("${spring.datasource.testOnBorrow:true}") privateBooleantestOnBorrow; @Value("${spring.datasource.testOnReturn:true}") privateBooleantestOnReturn; @Value("${spring.datasource.validationQuery:select1}") privateStringvalidationQuery; //@Value("${mybatis.mapper-locations}") //privateStringmapperLocations; @Bean publicDataSourcedataSource(){ DruidDataSourcedruidDataSource=newDruidDataSource(); druidDataSource.setUrl(url); druidDataSource.setDriverClassName(driverClassName); druidDataSource.setUsername(username); druidDataSource.setPassword(password); druidDataSource.setInitialSize(initialSize); druidDataSource.setMaxActive(maxActive); druidDataSource.setMaxWait(maxWait); druidDataSource.setMinIdle(minIdle); druidDataSource.setTestWhileIdle(testWhileIdle); druidDataSource.setTestOnBorrow(testOnBorrow); druidDataSource.setTestOnReturn(testOnReturn); druidDataSource.setValidationQuery(validationQuery); returndruidDataSource; } //privateResource[]resolveMapperLocations(){ //ResourcePatternResolverresourceResolver=newPathMatchingResourcePatternResolver(); //String[]arr=mapperLocations.split(","); //Listlocations=Arrays.asList(arr); //List resources=newArrayList(); //if(locations!=null){ //for(StringmapperLocation:locations){ //try{ //Resource[]mappers=resourceResolver.getResources(mapperLocation); //resources.addAll(Arrays.asList(mappers)); //}catch(IOExceptione){ ////ignore //} //} //} //returnresources.toArray(newResource[resources.size()]); //} @Bean publicSqlSessionFactorysqlSessionFactory()throwsException{ MybatisSqlSessionFactoryBeansqlSessionFactoryBean=newMybatisSqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource()); MybatisConfigurationconfiguration=newMybatisConfiguration(); configuration.setMapUnderscoreToCamelCase(true); configuration.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class); sqlSessionFactoryBean.setConfiguration(configuration); //sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations()); sqlSessionFactoryBean.setPlugins(newInterceptor[]{newPaginationInterceptor()}); returnsqlSessionFactoryBean.getObject(); } @Bean publicDataSourceTransactionManagertransactionManager(){ DataSourceTransactionManagertransactionManager=newDataSourceTransactionManager(); transactionManager.setDataSource(dataSource()); returntransactionManager; } }
问题解决!
以上这篇解决Mybatis-Plus操作分页后数据失效问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。