SpringBoot整合MyBatis(整合分页插件)

1 .数据准备

# 建库
drop database if exists mydb;
create database mydb default charset utf8;
use mydb;
# 建表
create table book
(
    id     int unsigned auto_increment,
    name   varchar(255),
    author varchar(255),
    price  decimal(6, 1),
    primary key (id)
);
# 初始化book表的数据
use mydb;
insert into book
values (null, '《Java实战》', '张三', 80.5),
       (null, '《深入Java虚拟机》', '李四', 80),
       (null, '《PHP》', '王五', 25),
       (null, '《Html、CSS、JS入门实战》', '赵六', 33.5),
       (null, '《C++就业实战》', '赵四', 60),
       (null, '《C语言入门》', '王二', 60),
       (null, '《Golang入门到精通》', '唐三', 60),
       (null, '《.NET实战案例》', '小舞', 66),
       (null, '《Android入门开发》', '胡烈娜', 88.0),
       (null, '《Android高级》', '比比东', 52.0),
       (null, '《Java并发编程的艺术》', '华少', 26.0),
       (null, '《三天精通Python》', '李三', 36);

2 .添加依赖


    
    
        org.springframework.boot
        spring-boot-starter
        2.6.6
    
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
        2.6.6
    
    
    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        2.2.2
    
    
    
        mysql
        mysql-connector-java
        8.0.28
    
    
    
        org.projectlombok
        lombok
        1.18.24
    
    
    
        com.github.pagehelper
        pagehelper-spring-boot-starter
        1.4.1
    

3 .准备Java类

  1. 实体类entity

@Data
 public class Book {
     private String id;
     private String name;
     private String author;
     private double price;
 }
  1. Mapper接口

 @Mapper
 public interface BookMapper {
     List queryAll();
 }
  1. 启动类

 @SpringBootApplication
 public class App {
     public static void main(String[] args) {
         SpringApplication.run(App.class, args);
     }
 }

5 .准备xml映射文件




    

6 .application.yml配置

spring:
  #数据源配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3308/mydb
# mybatis相关配置
mybatis:
  mapper-locations:
    - classpath:mybatis/mapper/*.xml #mapper映射路径
  type-aliases-package: cn.shun.entity #实体别名包扫描
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #配置sql日志输出

# 分页插件相关配置
pagehelper:
  helper-dialect: mysql #mysql数据库
  reasonable: true #分页合理化
  support-methods-arguments: true
SpringBoot整合MyBatis(整合分页插件)_第1张图片

注意.xml文件路径,与application.yml中mapper-locations一致

7 .测试

编写springboot测试类,测试类注意应建在主程序App所在包以及子包下,不然扫不到

/**
 * 

Project: Mybatis_beiyou-PACKAGE_NAME-cn.shun.mapper.T1 *

Powered by yishun On 2023-03-13 11:00:55 * * @author yishun [[email protected]] * @version 1.0 * @since 17 */ @SpringBootTest public class BookMapperTest { @Autowired private BookMapper bookMapper; @Test void t1() { PageHelper.startPage(2,5);//第一个参数为页码,第二个参数为每页显示数量 bookMapper.queryAll(); } }

8 .整合结果

SpringBoot整合MyBatis(整合分页插件)_第2张图片

你可能感兴趣的:(MyBatis,mybatis,spring,boot,java)