MyBatis学习笔记

分页插件

目标

  • 实现动态地按页查找记录

原理

  • 对应sql语句中limit关键字的用法
  • limit(startIndex, pageSize),其中startIndex表示起始坐标,pageSize表示查询的记录条数 

PageHelper插件

使用

  • 引入依赖
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>版本号</version>
</dependency>
  • 在mybatis-config.xml中配置分页的拦截器
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
  •  开启分页功能
PageHelper.startPage(pageNum, pageSize);
  • 封装分页信息
PageInfo<Car> car = new PageInfo<Car>(cars, Integer navigatePages);
  •  可以通过get方法获取分页信息

注解式开发

原则

  • 复杂的sql语句使用xml开发,简单的sql语句使用注解式方法

优点

  • 使用注解式开发,sql语句是写在java程序中,可以减少sql映射文件的配置

缺点

  • 但是,也会给sql语句的维护带来成本

使用(以t_car为例)

在接口文件中,对相应的方法添加相应的注解,其中value填入对应sql语句

  • 增
@Insert("insert into t_car(id, car_num, brand, guide_price, produce_time, car_type) values(#{id},#{carNum},#{brand},#{guidePrice},#{produceTime},#{carType})")
int insert(Car car);
  • 删
@Delete("delete from t_car where id = #{id}")
int delete(@Param("id")Long id);
  • 改
@Update("update t_car set car_num = #{carNum}, brand = #{brand}, guide_price = #{guidePrice} where id = #{id}")
int update(Car car);
  • 查
@Select("select * from t_car where car_type = #{carType}")
Car select(@Param("carType")String carType);

 

posted @ 2023-01-08 23:16  洋山芋芋  阅读(33)  评论(0)    收藏  举报