SpringBoot 整合MyBatis、PageHelper

一、新建项目

1.1 配置项目相关信息

SpringBoot 整合MyBatis、PageHelper

1.2 配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cyl</groupId>
    <artifactId>springboot-02</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--导入springboot父依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.7</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <!--打包的名字-->
        <finalName>springboot02</finalName>
        <plugins>
            <!--Spring Boot提供的,可以将项目打成可执行的jar包-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

1.3 配置文件中 配置数据源

src\main\resources\application.properties

server.port=8000

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 三个斜杆表示省略了部分,同:jdbc:mysql://localhost:3306/et2107?serverTimezone=UTC
spring.datasource.url=jdbc:mysql:///mydb?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=

1.4 启动类中配置控制层

package com.cyl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

/**
 *  @SpringBootApplication 由以下三个组成
 * 1.@SpringBootConfiguration 配置,不重要
 * 2.@EnableAutoConfiguration
 * 3.@ComponentScan 默认从启动类所在包向下扫描
 */
@SpringBootApplication
public class BootApp {

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

    @RestController
    public class TestController{

        @Autowired
        DataSource dataSource;

        /* 测试
        默认数据源:为 com.zaxxer.hikari.HikariDataSource
         */
        @GetMapping("/test")
        public Object test(){
            return dataSource.getClass().getName();
        }
    }
}

二、Spring Boot中使用默认数据源

  1. 数据源作用
    配置数据库连接参数
    可以提前创建数据库连接,减少了创建连接的开销
  2. Spring Boot 1.x 默认数据源是tomcat-jdbc
  3. Spring Boot 2.x 默认数据源是 HikariCP,又叫做
  4. Spring Boot整合默认数据源的Maven依赖: spring-boot-starter-jdbc
    SpringBoot 整合MyBatis、PageHelper
  5. 虽然能自动创建数据源,但是数据源连接参数需要用户提供
  6. 运行项目,输入正确url值
    SpringBoot 整合MyBatis、PageHelper

三、整合MyBatis

  1. Spring官方没有提供与MyBatis整合的starter依赖
  2. MyBatis官方提供了一个starter依赖整合Spring Boot的包
  3. Maven依赖
	<dependency>
		<groupId>org.mybatis.spring.boot</groupId>
		<artifactId>mybatis-spring-boot-starter</artifactId>
		<version>2.1.1</version>
	</dependency>
  1. 最小配置

在application.properties中配置mapperLocations

	mybatis.mapper-locations=classpath:mapper/*.xml

在启动类上使用@MapperScan注解
SpringBoot 整合MyBatis、PageHelper

四、 整合PageHelper

  1. Spring官方没有提供与PageHelper整合的starter依赖
  2. PageHelper官方提供了一个starter依赖整合Spring Boot
  3. Maven依赖
	<dependency>
		<groupId>com.github.pagehelper</groupId>
		<artifactId>pagehelper-spring-boot-starter</artifactId>
		<version>1.2.13</version>
	</dependency>

五、开始整合

5.1 导入MyBatis和PageHelper两个整合依赖

5.2 MyBatia相关配置

src\main\resources\application.properties

	mybatis.mapper-locations=classpath:mapper/*.xml

src\main\java\com\etoak\BootApp.java

	/*
	作用:指定要变成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类
	添加位置:是在Springboot启动类上面添加,
	 */
	@MapperScan(basePackages = "com.cyl.mapper")

5.3 编写代码

  1. 实体类
    src\main\java\com\etoak\entity\User.java
package com.cyl.entity;

import lombok.Data;

@Data
public class User {

    private Integer id;

    private String name;

    private String password;

    private String email;

    private String hobbies;

    private String createTime;
}
  1. mapper接口
    src\main\java\com\etoak\mapper\UserMapper.java
package com.cyl.mapper;

import com.cyl.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {

    List<User> getUser(@Param("name") String name);
}

  1. mapper映射文件
    src\main\resources\mapper\UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cyl.mapper.UserMapper">

    <select id="getUser" parameterType="String" resultType="com.cyl.entity.User">
        select
            id,
            name,
            email,
            age,
            hobbies,
            create_time as createTime
        from tb_user
        <where>
            <if test="name != null and name != ''">
                <!--AND name like '%${name}%'-->
                <!--前面别写%,影响索引-->
                AND name like concat(#{name},'%')
            </if>
        </where>
    </select>

</mapper>
  1. 分页 业务对象VO
package com.cyl.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageVO<T> {
    private Integer pageNumber;

    private Integer pageSize;

    private List<T> rows;

    private Long total;
}
  1. 控制层
    src\main\java\com\etoak\controller\UserController.java
package com.etoak.controller;

import com.etoak.entity.User;
import com.etoak.mapper.UserMapper;
import com.etoak.vo.PageVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @GetMapping("/list")
    public PageVO<User> getUser(@RequestParam(required = false,defaultValue = "1") int pageNumber,
                                @RequestParam(required = false,defaultValue = "10") int pageSize,
                                String name){
        //设置分页条件
        PageHelper.startPage(pageNumber, pageSize);
        //查询用户列表
        List<User> userList = userMapper.getUser(name);
        //插件PageInfo
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        //创建PageVO
        PageVO<User> pageVO = new PageVO<>(pageInfo.getPageNum(),
                                           pageInfo.getSize(),
                                           userList,
                                           pageInfo.getTotal());
        return pageVO;
    }

}

5.4 启动项目,输入正确url

此处我安装了在谷歌浏览器中安装了可以 json 数据化的插件,想了解请戳这里

SpringBoot 整合MyBatis、PageHelper

上一篇:Mybatis分页插件PageHelper返回分页属性大全


下一篇:寻找写代码感觉(十一)之使用PageHelper实现后端分页