Mybatis (3)-----分页的运用

这篇具有很好参考价值的文章主要介绍了Mybatis (3)-----分页的运用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

一、分页查询

二,特殊的字符处理

三、总结


前言:在我们上篇已经学的动态sql的基础上,今天继续讲解关于maybatis的分页,特殊的字符处理。希望这篇博客可以帮助到大家哦!

一、分页查询

为什么要重写mybatis的分页?

重写MyBatis的分页功能有几个原因。

首先,MyBatis默认的分页功能只能实现简单的分页,无法满足复杂的分页需求。通过重写MyBatis的分页,可以实现更灵活、更高级的分页功能。 其次,重写分页可以提高系统的性能。

其次,MyBatis的默认分页实现是通过在数据库查询时先查询出所有的结果,然后再根据分页参数进行结果的筛选。当数据量较大时,这种方式会导致查询的性能下降,甚至出现内存溢出的问题。通过重写分页,可以在数据库查询时直接生成带有分页语句的SQL,避免不必要的数据加载和内存消耗,从而提高系统的性能。 此外,重写分页还可以兼容不同的数据库方言。不同的数据库在分页语法上有一些差异,MyBatis默认的分页实现只适用于某些数据库,无法兼容所有的数据库。通过重写分页,可以根据不同的数据库方言生成相应的分页语句,从而实现跨数据库的分页功能。 因此,重写MyBatis的分页功能可以满足更复杂的分页需求,提高系统的性能,并兼容不同的数据库方言。

自定义使用分页插件步奏:
1、导入pom依赖

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

要找对文件夹目录,不然问题大大。Mybatis (3)-----分页的运用,mybatis,java,开发语言
2、Mybatis.cfg.xml配置拦截器

<plugins>
    <!-- 配置分页插件PageHelper, 4.0.0以后的版本支持自动识别使用的数据库 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
    </plugin>
</plugins>

Mybatis (3)-----分页的运用,mybatis,java,开发语言

3、使用PageHelper进行分页

package com.lya.util;
 
 
 
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;
/**
 * @authorlya
 * @site www.lya.com
 * @create  2023-08-24 11:44
 */
public class PageBean implements Serializable {
 
    private static final long serialVersionUID = 2422581023658455731L;
 
    //页码
    private int page=1;
    //每页显示记录数
    private int rows=10;
    //总记录数
    private int total=0;
    //是否分页
    private boolean isPagination=true;
    //上一次的请求路径
    private String url;
    //获取所有的请求参数
    private Map<String,String[]> map;
 
    public PageBean() {
        super();
    }
 
    //设置请求参数
    public void setRequest(HttpServletRequest req) {
        String page=req.getParameter("page");
        String rows=req.getParameter("rows");
        String pagination=req.getParameter("pagination");
        this.setPage(page);
        this.setRows(rows);
        this.setPagination(pagination);
        this.url=req.getContextPath()+req.getServletPath();
        this.map=req.getParameterMap();
    }
    public String getUrl() {
        return url;
    }
 
    public void setUrl(String url) {
        this.url = url;
    }
 
    public Map<String, String[]> getMap() {
        return map;
    }
 
    public void setMap(Map<String, String[]> map) {
        this.map = map;
    }
 
    public int getPage() {
        return page;
    }
 
    public void setPage(int page) {
        this.page = page;
    }
 
    public void setPage(String page) {
        if(null!=page&&!"".equals(page.trim()))
            this.page = Integer.parseInt(page);
    }
 
    public int getRows() {
        return rows;
    }
 
    public void setRows(int rows) {
        this.rows = rows;
    }
 
    public void setRows(String rows) {
        if(null!=rows&&!"".equals(rows.trim()))
            this.rows = Integer.parseInt(rows);
    }
 
    public int getTotal() {
        return total;
    }
 
    public void setTotal(int total) {
        this.total = total;
    }
 
    public void setTotal(String total) {
        this.total = Integer.parseInt(total);
    }
 
    public boolean isPagination() {
        return isPagination;
    }
 
    public void setPagination(boolean isPagination) {
        this.isPagination = isPagination;
    }
 
    public void setPagination(String isPagination) {
        if(null!=isPagination&&!"".equals(isPagination.trim()))
            this.isPagination = Boolean.parseBoolean(isPagination);
    }
 
    /**
     * 获取分页起始标记位置
     * @return
     */
    public int getStartIndex() {
        //(当前页码-1)*显示记录数
        return (this.getPage()-1)*this.rows;
    }
 
    /**
     * 末页
     * @return
     */
    public int getMaxPage() {
        int totalpage=this.total/this.rows;
        if(this.total%this.rows!=0)
            totalpage++;
        return totalpage;
    }
 
    /**
     * 下一页
     * @return
     */
    public int getNextPage() {
        int nextPage=this.page+1;
        if(this.page>=this.getMaxPage())
            nextPage=this.getMaxPage();
        return nextPage;
    }
 
    /**
     * 上一页
     * @return
     */
    public int getPreivousPage() {
        int previousPage=this.page-1;
        if(previousPage<1)
            previousPage=1;
        return previousPage;
    }
 
    @Override
    public String toString() {
        return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
                + "]";
    }
}

4、处理分页结果

①BookBiz

List<Map> listPager(Map map, PageBean pageBean);


②BookMapper.java

//    利用第三方插件进行分页
    List<Map> listPager(Map map);


③BookMapper.xml

<select id="listPager" resultType="java.util.Map" parameterType="java.util.Map">
  select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%')
</select>


④BookBizImpl

@Override
    public List<Map> listPager(Map map, PageBean pageBean) {
//        pageHelper分页插件相关的代码
        if(pageBean!=null&&pageBean.isPagination()){
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
        }
        List<Map> maps = bookMapper.listPager(map);
        if(pageBean!=null&&pageBean.isPagination()){
//            处理查询结果的前提是需要分页,是需要分页的
            PageInfo info = new PageInfo(maps);
            pageBean.setTotal(info.getTotal()+"");
        }
        return maps;
    }


⑤BookBizImplTest 

@Test
    public void listPager() {
        Map map=new HashMap();
        map.put("bname","圣墟");
//        bookBiz.listPager(map).forEach(System.out::println);
 
//        查询出第二页的20条数据
        PageBean pageBean = new PageBean();
        pageBean.setPage(2);
        pageBean.setRows(20);
 
        bookBiz.listPager(map,pageBean).forEach(System.out::println);

   

}

二,特殊的字符处理

二、模糊查询
 我们在写模糊查询的时候一般是这样写的:

select * from t_mvc_book where bname like '%?%'

然后我们便使用占位符在后台进行传值进行查询

那么使用Mybatis只后会有所不同,他有三种方式改变这个模糊查询的方式:

  <select id="selectBooksLike1" resultType="com.zq.model.Book" parameterType="java.lang.String">
  select * from t_mvc_book where bname like #{bname}
</select>
  <select id="selectBooksLike2" resultType="com.zq.model.Book" parameterType="java.lang.String">
  select * from t_mvc_book where bname like '${bname}'
</select>
  <select id="selectBooksLike3" resultType="com.zq.model.Book" parameterType="java.lang.String">
  select * from t_mvc_book where bname like concat('%',#{bname},'%')
</select>


 写完这些xml文件的配置后我们将其他的biz层也加入进来

BookMapper.xml:
 


<select id="listPagerS" resultType="com.csdn.xw.model.Book" parameterType="java.util.Map">
  select * from t_mvc_book where bname like concat(concat('%',#{bname}),'%') and price < #{max}
</select>

BookBizImplTest 

 @Test
    public void listPagerS() {
        System.out.println("没有处理特殊字符之前");
        Map map=new HashMap();
        map.put("dname","圣墟");
        map.put("max",20);
        bookBiz.listPagerS(map).forEach(System.out::println);
 @Test
    public void listPagerS() {
        System.out.println("没有处理特殊字符之前");
        Map map=new HashMap();
        map.put("dname","圣墟");
        map.put("max",20);
        bookBiz.listPagerS(map).forEach(System.out::println);


 

三、总结

   我们在使用myBatis的时候,在做sql的配置文件的时候会发现一个问题,就是会出现特殊字符和标签括号冲突问题

比如:<  和<

什么意思?就是第一个是判断符号小于,第二个是标签的左括号,那么怎么区别呢?有两种方式:

①: <![CDATA[ <= ]]> 

②:    <(&lt;)  、    >(&gt;)       &(&amp;) 

举例说明:

  ①BookBiz

 
 
  1. List<Book> list6(BookVo bookVo);

  2. List<Book> list7(BookVo bookVo);

②BookMapper.java

/**
     * 处理特殊字符
     * @param bookVo
     * @return
     */
    List<Book> list6(BookVo bookVo);
 
 
    /**
     * 处理特殊字符
     * @param bookVo
     * @return
     */
    List<Book> list7(BookVo bookVo);


③BookMapper.xml

<select id="list6" resultType="com.zq.model.Book" parameterType="com.zq.model.BookVo">
  select * from t_mvc_book
  <where>
    <if test="null != min and min != ''">
      <![CDATA[  and #{min} < price ]]>
    </if>
    <if test="null != max and max != ''">
      <![CDATA[ and #{max} >
  </where>
</select>
 
<select id="list7" resultType="com.javaxl.model.Book" parameterType="com.zq.model.BookVo"> price ]]>
    </if>
    select * from t_mvc_book
    <where>
      <if test="null != min and min != ''">
         and #{min} &lt; price
      </if>
      <if test="null != max and max != ''">
         and #{max} &gt; price
      </if>
    </where>
  </select>

④BookBizImpl

@Override
    public List<Book> list6(BookVo bookVo) {
        return bookMapper.list6(bookVo);
    }
 
    @Override
    public List<Book> list7(BookVo bookVo) {
        return bookMapper.list7(bookVo);
    }

⑤BookBizImplTest

 @Test
    public void list6() {
        BookVo vo=new BookVo();
        vo.setMax(45);
        vo.setMin(35);
        bookBiz.list6(vo).forEach(System.out::println);
    }
 
    @Test
    public void list7() {
        BookVo vo=new BookVo();
        vo.setMax(45);
        vo.setMin(35);
        bookBiz.list7(vo).forEach(System.out::println);
    }

测试结果:

Mybatis (3)-----分页的运用,mybatis,java,开发语言文章来源地址https://www.toymoban.com/news/detail-671453.html

到了这里,关于Mybatis (3)-----分页的运用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 后端项目开发:分页功能的实现(Mybatis+pagehelper)

    分页查询是项目中的常用功能,此处我们基于Mybatis对分页查询进行处理。 引入分页依赖 在http目录下,新建PageResult类,我们用此类包装分页结果。

    2024年02月11日
    浏览(32)
  • java springboot整合MyBatis实现分页查询以及带条件的分页查询

    之前的文章 java springboot整合MyBatis做数据库查询操作操作了springboot整合MyBatis,然后简单做了个按id查询的操作 那么 我们按上文搭建起的环境继续 我们直接在staffDao接口中声明一个分页函数 这里 我们直接在 sql语句中写limit 分页逻辑 参数是方法接收的 这个函数接收两个参数

    2024年02月10日
    浏览(35)
  • MyBatis:生命周期、作用域、结果集映射 ResultMap、日志、分页、使用注解开发、Lombok

    理解不同 作用域 和 生命周期 类别是至关重要的,因为错误的使用会导致非常严重的 并发问题 。 SqlSessionFactoryBuilder 一旦创建了 SqlSessionFactory,就不再需要它了; 最佳作用域 是方法作用域(也就是局部方法变量)。 SqlSessionFactory :相当于 数据库连接池 一旦被创建就应该在

    2024年02月02日
    浏览(44)
  • Mybatis-Plus详解(新建maven项目、查询所有信息、打印SQL日志、实现CRUD(增删改查)、分页、条件查询且分页,前后端分离式开发)

    MyBatis-Plus(opens new window) (简称MP) 是一个MyBatis(opens new window)的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。想查看官网相关内容的化我这里提供了官网地址:https://baomidou.com/ 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般

    2024年02月04日
    浏览(54)
  • Java语言开发在线小说推荐网 小说推荐系统 基于用户、物品的协同过滤推荐算法 SSM(Spring+SpringMVC+Mybatis)开发框架 大数据、人工智能、机器学习开发

    1、开发工具和使用技术 MyEclipse10/Eclipse/IDEA,jdk1.8,mysql5.5/mysql8,navicat数据库管理工具,tomcat,SSM(spring+springmvc+mybatis)开发框架,jsp页面,javascript脚本,jquery脚本,bootstrap前端框架(用户端),layui前端框架(管理员端),layer弹窗组件等。 2、实现功能 前台用户包含:注

    2023年04月26日
    浏览(57)
  • MyBatis之分页查询:MyBatis PageHelper

    MyBatis,作为目前流行的ORM框架,大大方便了日常开发。而对于分页查询,虽然可以通过SQL的limit语句实现,但是比较繁琐。而MyBatis PageHelper的出现,则解决了这一痛点。这里将介绍如何在Spring Boot、MyBatis的环境中通过MyBatis PageHelper高效方便的实现分页查询 添加Maven依赖 添加配

    2024年02月09日
    浏览(25)
  • MyBatis 03 -MyBatis动态SQL与分页插件

    MyBatis的映射文件中支持在基础SQL上添加一些逻辑操作,并动态拼接成完整的SQL之后再执行,以达到SQL复用、简化编程的效果。 动态查询 where标签和if标签组合使用 动态修改 1.1 sql sql标签的作用是提取公共的sql代码片段 sql id属性:唯一标识 include refid属性:参照id 动态查询

    2023年04月15日
    浏览(32)
  • MyBatis与MyBatis-Plus的分页以及转换

    MyBatis和MyBatis-Plus都是Java持久化框架,用于简化数据库访问和操作。它们提供了面向对象的方式来管理关系型数据库中的数据。 MyBatis 是一个轻量级的持久化框架,通过XML或注解配置,将SQL语句与Java对象进行映射,使开发者可以使用简单的API来执行数据库操作。MyBatis支持动态

    2024年02月11日
    浏览(44)
  • mybatis-plus分页total为0,分页失效,mybatis-plus多租户插件使用

    背景:项目使用mybatis分页插件不生效,以及多租户使用时读取配置异常 多租户插件使用遇到的问题: 最开始在MyTenantLineHandler中使用 @Value(\\\"${tables}\\\"),服务启动时能从配置中心拉取到配置,但在运行时获取到的值为空,试了很多方法都不生效,后面将配置中心的配置在调用My

    2024年02月06日
    浏览(41)
  • MyBatis分页插件

    分页插件使用。 添加依赖 配置分页插件 在MyBatis的核心配置文件(mybatis-config.xml)中配置插件 开启分页功能 在查询功能之前使用 PageHelper.startPage(int pageNum, int pageSize) 开启分页功能 pageNum:当前页的页码 pageSize:每页显示的条数 分页相关数据 方法一:直接输出 分页相关数据

    2024年02月09日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包