• 【零基础入门MyBatis系列】第十五篇——分页插件与注解式开发


    一、概述

    🌔 1、如何理解分页?

    在这里插入图片描述
    🌔 2、准备工作

    • 创建一个新模块:mybatis-014-page
      在这里插入图片描述
    • 除了CarMapper、CarMapper.xml、CarMapperTest三兄弟,其他的文件都是从之前的模块拷贝过来的
    • 操作的还是我们的 t_car
    • 本篇的主要内容:
      • 通过 limit 关键字我们自己模拟一下分页输出的效果
      • 导入并使用 PageHelper 插件

    二、limit 分页

    🌔 1、什么是 limit 关键字,如何使用?

    • mysqllimit关键字用来强制 SELECT 语句返回指定的记录数
    • 该关键字后一版跟着两个数:
      • 第一个数 startIndex 代表数据的起始位置
      • 第二个数 pageSize 代表显示的数据条数
    • 当该关键字后只有一个数的时候,代表起始位置是从 0 开始的
      在这里插入图片描述
      🌔 2、我们手写一个利用 limit 关键字的 SQL:

    (1)接口中的方法:【此处使用了@Param注解提高可读性】

    /**
    * 分页查询
    * @param startIndex 起始下标
    * @param pageSize 每页显示的记录条数
    * @return
    */
    List<Car> selectByPage(@Param("startIndex") int startIndex, @Param("pageSize") int pageSize);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    (2)映射文件中的SQL语句:

    <select id="selectByPage" resultType="Car">
    	select * from t_car limit #{startIndex}, #{pageSize}
    </select>
    
    • 1
    • 2
    • 3

    (3)测试类中的测试方法:

    @Test
    public void testSelectByPage() throws Exception{
    	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
    	SqlSession sqlSession = sqlSessionFactory.openSession();
    	CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    	// 固定我们的每页显示记录条数和起始位置
    	int pageNum = 2; //第几页
    	int pageSize = 2;
    	int startIndex = (pageNum - 1) * pageSize;
    	// 调用我们分页查询SQL
    	List<Car> cars = mapper.selectByPage(startIndex, pageSize);
    	cars.forEach(car -> System.out.println(car));
    	sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述
    我们查看表中的数据,确实显示的是第二页的两条数据

    在这里插入图片描述


    三、 PageHelper 插件

    🌔 1、什么是PageHelper插件?

    • 是一个很好的 mybatis 分页插件
    • 通过一些简单的配置就可以使用这个插件

    🌔 2、使用这个插件的流程是什么?

    (1)在 pom.xml 文件中引入相关依赖

    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.3.1</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (2)在mybatis核心配置文件 mybatis-config.xml 中进行配置

    <plugins>
      <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
    
    • 1
    • 2
    • 3

    (3)编写我们的接口方法

    /**
    * 利用分页插件查询
    * @return
    */
    List<Car> selectAll();
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (4)编写我们的 SQL 语句:【此处只需要查询全部数据,分页显示依靠插件完成】

    <select id="selectAll" resultType="Car">
    	select * from t_car
    </select>
    
    • 1
    • 2
    • 3

    (5)编写我们的测试方法

    @Test
    public void testSelectAll(){
    	SqlSession sqlSession = SqlSessionUtil.openSession();
    	CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    	int pageNum = 2;
    	int pageSize = 2;
    	// 开启我们的分页插件
    	PageHelper.startPage(pageNum, pageSize);
    	List<Car> cars = mapper.selectAll();
    	cars.forEach(car -> System.out.println(car));
    	PageInfo<Car> carPageInfo = new PageInfo<>(cars, 2);
    	System.out.println(carPageInfo);
    	sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

    • 想要使用我们的分页插件,只需要在执行查询之前开启我们的分页功能【传递两个参数,第几页、页大小】
    • 查询语句之后封装PageInfo对象。【将来会存储到request域当中,进而在前端页面上展示】
    • PageInfo 中的属性含义如下:
    属性名含义
    pageNum代表当前页号
    pageSize代表每页的数量
    size代表当前页的数量
    startRow代表当前页面第一个元素的行号
    endRow代表当前页面最后一个元素的行号
    total代表总记录数
    pages代表总记录数
    list代表查询结果集
    prePage上一页页号
    nextPage下一页页号
    isFirstPage是否为第一页
    isLastPage是否为最后一页
    hasPreviousPage是否有前一页
    hasNextPage是否有下一页
    navigatePages导航页码数
    navigatepageNums所有导航页号
    navigateFirstPage导航条上的第一页
    navigateLastPage导航条的最后一页

    四、注解开发

    🌔 1、注解开发的应用场景?

    • 适用于简单的SQL语句,内嵌在接口方法上,提高了维护成本
    • 注解映射看起来更简洁,但是对于复杂的语句并不适用

    🌔 2、准备工作?

    • 创建新模块: mybatis-015-annotation
    • 操作的表:t_car
    • 其他不变,只是此次三兄弟变成了两兄弟:CarMapper接口、CarMapperTest测试方法
    • 目录结构
      在这里插入图片描述

    🌔 3、@Insert 注解

    (1)接口方法

    @Insert(value = "insert into t_car values(null, #{carNum}, #{brand}, #{guidePrice}, #{produceTime}, #{carType})")
    int insert(Car car);
    
    • 1
    • 2

    (2)测试方法

    @Test
    public void testInsert() throws Exception{
    	SqlSessionFactory build = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
    	SqlSession sqlSession = build.openSession();
    	CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    	// 创建我们要插入的汽车对象
    	Car car = new Car(null, "103", "路虎", 200.0, "2022-11-09", "燃油车");
    	int count = mapper.insert(car);
    	System.out.println(count);
    	sqlSession.commit();
    	sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    (3)测试结果: 插入数据成功

    在这里插入图片描述

    🌔 4、@Delete注解

    (1)接口方法

    @Delete("delete from t_car where id = #{id}")
    int deleteById(Long id);
    
    • 1
    • 2

    (2)测试方法

    @Test
    public void testDeleteById() throws Exception{
    	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
    	SqlSession sqlSession = sqlSessionFactory.openSession();
    	CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    	int count = mapper.deleteById(29L);
    	System.out.println(count);
    	sqlSession.commit();
    	sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    (3)测试结果 >> 删除数据成功

    在这里插入图片描述

    🌔 5、@Update 注解

    (1)接口方法

    @Update("update t_car set car_num = #{carNum}, brand = #{brand}, guide_price = #{guidePrice}, produce_time = #{produceTime}, car_type = #{carType} where id = #{id}")
    int update(Car car);
    
    • 1
    • 2

    (2)测试方法

    @Test
    public void testUpdate() throws Exception{
    	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
    	SqlSession sqlSession = sqlSessionFactory.openSession();
    	CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    	Car car = new Car(32L, "", "宾利飞驰", 222.0, "2022-11-09", "燃油车");
    	int count = mapper.update(car);
    	System.out.println(count);
    	sqlSession.commit();
    	sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    (3)测试结果:更新数据成功

    在这里插入图片描述

    🌔 6、@Select 注解

    (1)接口方法

    @Select("select * from t_car where id = #{id}")
    Car selectById(Long id);
    
    • 1
    • 2

    (2)测试方法

    @Test
    public void testSelectById() throws Exception{
    	SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
    	SqlSession sqlSession = sqlSessionFactory.openSession();
    	CarMapper mapper = sqlSession.getMapper(CarMapper.class);
    	Car car = mapper.selectById(37L);
    	System.out.println(car);
    	sqlSession.close();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    (3)测试结果:输出指定id的数据
    在这里插入图片描述

    • 通过观察我们可以发现,此处select语句直接使用了 select *,可以正常输出是因为我们开启了驼峰自动映射机制
    • 如果我们没有开启,需要怎么处理呢?

    我们可以通过 @Result 注解来完成属性名与字段名的映射:【只需要在Select注解和方法间添加@result注解】

    @Results({
                @Result(property = "id", column = "id"),
                @Result(property = "carNum", column = "car_num"),
                @Result(property = "brand", column = "brand"),
                @Result(property = "guidePrice", column = "guide_price"),
                @Result(property = "produceTime", column = "produce_time"),
                @Result(property = "carType", column = "car_type"),
        })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

  • 相关阅读:
    【Vue项目复习笔记】商品评论信息的展示
    el-pagination分页分页设置
    Spectacle源码编译方法
    ubuntu安装rust教程
    flex布局独占一行实现方法
    手写简单promise
    选择排序.
    Python爬虫案例入门教程(纯小白向)——夜读书屋小说
    vscode 配置 lua
    统一最小二乘标准问题形式
  • 原文地址:https://blog.csdn.net/qq_61323055/article/details/127778629