PageHelper在Mybatis中的使用

 Mybtis中使用PageHelper中分为2中情况,第一种为采用springboot框架自动生成的Bean方式,第二种为自己数据库配置bean方式,以下分别讲解2种方式的使用:

一、自动生成的Bean配置PageHelper插件

1.导入PageHelper的相关jar包

<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>5.1.2</version>
</dependency>

2.在mybtis配置文件中添加插件配置并在yml文件中引用相关配置

<configuration>
  <plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
    <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 -->
    <!-- <property name="dialect" value="sqlite" /> -->
    </plugin>
</plugins>
</configurat

yml中的引用方式为:

# Mybatis配置
#mybatis:
# mapperLocations: classpath:mapper/**/*.xml
# configLocation: classpath:/mybatis.xml

 

3.使用方法

public PageInfo<Songs> selectList(Songs record) {
        if(record.getCurrentPage() != 0) {
            PageHelper.startPage(record.getCurrentPage(),record.getPageSize());
        }
        List<Songs> selectNowTotalList = songsMapper.selectTotalList(replaceCloum(record));
        return new PageInfo<>(selectNowTotalList);
    }

 二、自己手动书写Bean配置方式

 使用此方式配置则可以不需要mybatis的配置文件,因为此类就相当于之前的配置文件

1.导入相关jar包

2. 在bean中返回sqlSessionFactory方法中添加如下代码

    @Bean(name = "masterSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.xuanyin.pojo");
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        
        //添加PageHelper插件  
        Interceptor interceptor = new PageInterceptor();
        Properties properties = new Properties();
        //数据库
        properties.setProperty("helperDialect", "sqlite");
        //是否将参数offset作为PageNum使用
        properties.setProperty("offsetAsPageNum", "true");
        //是否进行count查询
        properties.setProperty("rowBoundsWithCount", "true");
        //是否分页合理化
        properties.setProperty("reasonable", "false");
        interceptor.setProperties(properties);
        factoryBean.setPlugins(new Interceptor[] {interceptor});
        
        return factoryBean.getObject();
    }

 

3.使用方法是上述一样

提示:springboot配置双数据源的时候,由于是自己书写的bean,故此也可以采用此种方式进行进行分页配置,springboot配置双数据源方式,可参考我的另一篇随笔:https://www.cnblogs.com/zblwyj/p/10892903.html

 单数据源自己手动书写bean不会的童鞋也可参考此片文章。

转载于:https://www.cnblogs.com/zblwyj/p/10893001.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值