MyBatis怎样实现MySQL动态分页

MyBatis怎样实现MySQL动态分页,第1张

原料,mybatis的jar包,各种数据库的分页sql语句

这就要看你是使用何种数据库了,因为有些数据库的分页实现可以更简单,比如MySql的limit关键字,而mybatis必须通过sql语句才能实现分页,所以在我们的<select>标签可以这样写:参数paramterType可以传一个封装了分页信息(比如当前页数,每页大小等)对象,如果是带条件的分页,可以将分页的对象和条件对象放入一个map中。然后在sql语句中就可以用#{}访问分页信息:

比如Mysql的分页:

select  *  from  Student  limit   #{pageSize*(pageNo-1)}  #{pageSize}

1、亲Mybatis是自己写Sql语句啊,和Hibernate不一样。

2、如何知道上面的,你还要知道MySql有一个分页语句叫limit,如:limit(1,10)前面一个参数是起始未知,后面一个是查询多少个。

3、Oracle的分页方法是嵌套子查询,需要用到rownum这个属性

Sql Server是Top。

分页例子:

Oracleselect * from (select emp.*,rownum rn from emp where rownum<9) where rn>3

MySql select * from emp limit startIndex,maxNum

配置mybatis属性,可以用mybatis-config.xml来配置,也可以使用@Configuration 注解的java类来实现。

1)在xml文件中加入pageHelper

<plugins>

<plugin interceptor="com.github.pagehelper.PageHelper">

<property name="dialect" value="mysql"></property>

<property name="offsetAsPageNum" value="true"></property>

<property name="rowBoundsWithCount" value="true"></property>

<property name="pageSizeZero" value="true"></property>

<property name="reasonable" value="false">(/property>

<property name="supportMethodsArguments" value="false">(/property>

<property name="returnPageInfo" value="none">(/property>

</plugin>

</plugins>

2)在注解类里加pageHelper

@Bean

public Interceptor pageHelper() {

PageHelper pageHelper = new PageHelper()

SqlUtilConfig config = new SqlUtilConfig()

config.setOffsetAsPageNum(true)

config.setRowBoundsWithCount(true)

config.setPageSizeZero(true)

config.setReasonable(true)

pageHelper.setSqlUtilConfig(config)

return pageHelper

注意: mybatis-config.xml 与 @Configuration 注解的java类 两种方式不宜混合使用。应只采取其中一种。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/8564716.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-18
下一篇2023-04-18

发表评论

登录后才能评论

评论列表(0条)

    保存