解决Mybatis-Plus操作分页后数据失效问题
业务场景
我们知道在使⽤PageHelper分页插件时,会对执⾏PageHelper.startPage(pageNum, pageSize);⽅法后的第⼀条查询语句进⾏分页操作。在开发中总会遇到这样的业务情景,在进⾏分页查询后,需要对获得的列表数据包装成另⼀种类型,此时需要对新类型的列表进⾏分页,然⽽由于PageInfo<T>因为泛型的原因,导致处理后的列表不能加⼊到该类中。
如,我在数据库分页后查询到的类为PageInfo<User>,此时改类中的list属性为User,在当前的业务场景下,我需要将User类型替换为UserVo类型。
当我们对list属性进⾏操作时,会同时导致PageInfo类中的其他属性发⽣改变,如total等。
解决⽅法
//从数据库获得的Users分页列表
//当我们打印users时,会发现打印出来的数据除了列表数据还有分页属性
List<User> users = this.list();
//操作users获得的需要的列表
List<UserVo> userVos = this.list2(users);
//创建User的info类,此时page中的属性已⽣成
PageInfo<User> userPage = new PageInfo<>(users);
//创建UserVo的info类
PageInfo<UserVo> userVoPage= new PageInfo<>(userVos );
//将userPage中除看list外的其他属性复制到userVoPage中
PageInfoUtil pageInfoUtil = new PageInfoUtil();
pageInfo = PageVo(userPage ,userVoPage);
pageInfoUtil
public class PageInfoUtil {
public PageInfo getPageVo(PageInfo pageInfoPo,PageInfo pageInfoVo){
pageInfoVo.Total());
pageInfoVo.EndRow());
pageInfoVo.setHasNextPage(pageInfoPo.isHasNextPage());
pageInfoVo.setHasPreviousPage(pageInfoPo.isHasPreviousPage());
pageInfoVo.setIsFirstPage(pageInfoPo.isIsFirstPage());
pageInfoVo.setIsLastPage(pageInfoPo.isIsLastPage());
pageInfoVo.NavigateFirstPage());
pageInfoVo.NavigateLastPage());
pageInfoVo.NavigatePages());
pageInfoVo.NavigatepageNums());
pageInfoVo.NextPage());
pageInfoVo.PageNum());
pageInfoVo.Pages());
pageInfoVo.PageSize());
pageInfoVo.PrePage());
pageInfoVo.Size());
pageInfoVo.StartRow());
pageInfoVo.FirstPage());
pageInfoVo.LastPage());
return pageInfoVo;
}
}
End
想使⽤秀⼀点的⽅法,结果能⼒有限,没有成功,只能使⽤这种笨⽅法,如果有更好的⽅法,欢迎各位指导。
补充知识:mybatis-plus分页⽆效, total=0问题(springmvc)
前⾔
项⽬中(springmvc)分页采⽤mybatis-plus, 头⼀回⽤, 就遇到了如题问题
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.2.0</version>
</dependency>
mapper继承了BaseMapper
@Repository
public interface UserMapper extends BaseMapper<UserPo>{
// 这⾥代码没⽤, 查询采⽤的BaseMapper中的 IPage<T> selectPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper); }
service层
@Override
public SysUserVo list(UserQo qo) {
QueryWrapper<UserPo> queryWrapper = new QueryWrapper<>();
queryWrapper.like("name", qo.getKeyword())
.or().
like("code", qo.getKeyword());
Page<UserPo> page = new Page<>(qo.getPageNo(), qo.getPageSize());
IPage<UserPo> userPoIPage = userMapper.selectPage(page, queryWrapper);
List<UserPo> records = Records();
long total = Total();// 总记录数
long pages = Pages();// 查询结果数
long pageNo = Current();// 当前页
long pageSize = Size();// 每页条数
List<UserVo> userVos = wArrayList();
for (UserPo userPo : records) {
Integer userId = Id();
List<RolePo> roles = userMapper.selectRoles(userId);
UserVo userVo = UserVo.builder().Code())
.Name())
.rolePo(roles)
.Status())
.build();
userVos.add(userVo);
}
SysUserVo sysUserVo = SysUserVo.builder()
.list(userVos)
.total(total)
.
build();
return sysUserVo;
}
结果分页并没有⽣效, 于是添加
fig;
import sion.plugins.PaginationInterceptor;
import sion.plugins.pagination.optimize.JsqlParserCountOptimize;
batis.spring.annotation.MapperScan;
import t.annotation.Bean;
import t.annotation.Configuration;
import ansaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@MapperScan("bbank.api.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页⾯⼤于最⼤页后操作, true调回到⾸页,false 继续请求默认false
paginationInterceptor.setOverflow(true);
// 设置最⼤单页限制数量,默认 500 条,-1 不受限制
paginationInterceptor.setLimit(100);
/
/ 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
paginationInterceptor.setDialectType("mysql");
return paginationInterceptor;
}
}
还是没⽣效
分页查询插件最后到解决⽅案, 在数据源配置中显式添加分页插件
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setMapUnderscoreToCamelCase(true);
configuration.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class);
sqlSessionFactoryBean.setConfiguration(configuration);
// sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations());
sqlSessionFactoryBean.setPlugins(new Interceptor[]{new PaginationInterceptor()}); Object();
}
完整配置
fig;
import com.alibaba.druid.pool.DruidDataSource;
import MybatisConfiguration;
import sion.plugins.PaginationInterceptor;
import sion.spring.MybatisSqlSessionFactoryBean; import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.pe.EnumOrdinalTypeHandler;
batis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import t.annotation.Bean;
import t.annotation.Configuration;
import t.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource;
/**
* @author linyong
* @date 2020/7/30 16:38
* @description 数据源配置
**/
@Configuration
@EnableAspectJAutoProxy
@MapperScan("bbank.api.mapper")
public class DBConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.initialSize:5}")
private Integer initialSize;
@Value("${spring.datasource.maxActive:50}")
private Integer maxActive;
@Value("${spring.datasource.maxWait:60000}")
private Integer maxWait;
@Value("${spring.datasource.minIdle:5}")
private Integer minIdle;
@Value("${stWhileIdle:true}")
private Boolean testWhileIdle;
@Value("${stOnBorrow:true}")
private Boolean testOnBorrow;
@Value("${stOnReturn:true}")
private Boolean testOnReturn;
@Value("${spring.datasource.validationQuery:select 1}")
private String validationQuery;
// @Value("${mybatis.mapper-locations}")
// private String mapperLocations;
@Bean
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
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);
return druidDataSource;
}
// private Resource[] resolveMapperLocations() {
// ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
/
/ String[] arr = mapperLocations.split(",");
// List<String> locations = Arrays.asList(arr);
// List<Resource> resources = new ArrayList();
// if (locations != null) {
// for (String mapperLocation : locations) {
// try {
// Resource[] mappers = Resources(mapperLocation);
// resources.addAll(Arrays.asList(mappers));
// } catch (IOException e) {
// // ignore
// }
/
/ }
// }
// Array(new Resource[resources.size()]);
// }
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setMapUnderscoreToCamelCase(true);
configuration.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class);
sqlSessionFactoryBean.setConfiguration(configuration);
// sqlSessionFactoryBean.setMapperLocations(resolveMapperLocations());
sqlSessionFactoryBean.setPlugins(new Interceptor[]{new PaginationInterceptor()});
Object();
}
@Bean
public DataSourceTransactionManager transactionManager(){
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource());
return transactionManager;
}
}
问题解决!
以上这篇解决Mybatis-Plus操作分页后数据失效问题就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论