SpringBoot整合Mybatis和PageHelper实现分页查询(含源码)

  1. PageHalper是Mybatis中的一个分页插件,支持众多的数据库,使用很简单

  2. 下面介绍SpringBoot整合Mybatis和PageHelper实现分页查询的功能

  3. 新建一个SpringBoot项目,项目的结构如下

  4. 添加下面的依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- pagehelper依赖 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.9</version>
        </dependency>
        <!-- mybatis-generator依赖 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
  5. 添加mybatis-generator插件用于自动生成相关的代码

    <plugin>
        <groupId>org.mybatis.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <configuration>
            <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
            <verbose>true</verbose>
            <overwrite>true</overwrite>
        </configuration>
        <executions>
            <execution>
                <id>Generate MyBatis Artifacts</id>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
        <dependencies>
            <dependency>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-core</artifactId>
                <version>1.3.2</version>
            </dependency>
        </dependencies>
    </plugin>
    
  6. 对于不熟悉mybatis-generator的请参考

    SpringBoot整合Mybatis和Mybatis-generator实现代码自动生成

  7. 在resources下新建mybatis-generator的配置文件generatorConfig.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration
            PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    <generatorConfiguration>
        <!--本机数据库驱动jar包存放目录-->
        <classPathEntry    location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\5.1.42\mysql-connector-java-5.1.42.jar"/>
        <context id="DB2Tables"    targetRuntime="MyBatis3">
            <commentGenerator>
                <property name="suppressDate" value="true"/>
                <property name="suppressAllComments" value="true"/>
            </commentGenerator>
            <!--数据库驱动,数据库地址及表名,账号,密码-->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test"    userId="root" password="root">
            </jdbcConnection>
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
            <!--生成Model类的包名及存放位置-->
            <javaModelGenerator targetPackage="com.kangswx.springbootmybatispagehelper.entity" targetProject="src/main/java">
                <property name="enableSubPackages" value="true"/>
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
            <!--生成映射文件的包名及存放位置-->
            <sqlMapGenerator targetPackage="com.kangswx.springbootmybatispagehelper.mapper.mapping" targetProject="src/main/java">
                <property name="enableSubPackages" value="true"/>
            </sqlMapGenerator>
            <!--生成Dao类的包名及存放位置-->
            <javaClientGenerator type="XMLMAPPER" targetPackage="com.kangswx.springbootmybatispagehelper.mapper" targetProject="src/main/java">
                <property name="enableSubPackages" value="true"/>
            </javaClientGenerator>
            <!--生成对应表及类名,domainObjectName是设置实体类的名字的-->
            <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        </context>
    </generatorConfiguration>
    
  8. 在resources\mybatis下添加Mybatis的配置文件config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <settings>
            <!--配置命名规则-->
            <setting name="mapUnderscoreToCamelCase" value="true" />
        </settings>
        <typeAliases>
            <typeAlias alias="Integer" type="java.lang.Integer" />
            <typeAlias alias="Long" type="java.lang.Long" />
            <typeAlias alias="HashMap" type="java.util.HashMap" />
            <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
            <typeAlias alias="ArrayList" type="java.util.ArrayList" />
            <typeAlias alias="LinkedList" type="java.util.LinkedList" />
        </typeAliases>
    </configuration>
    
  9. 将application.properties修改为application.yml,并加入下面的配置项

    server:
      port: 8081
    
    #数据库配置项
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
        username: root
        password: root
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
    
    #mybatis配置项
    mybatis:
      config-location: classpath:mybatis/config.xml
      mapper-locations: classpath*:mybatis/mapper/**/*.xml
    
    #pagehelper配置项
    pagehelper:
      helper-dialect: mysql
      reasonable: true
      support-methods-arguments: true
      params: count=countsql
    
    #打印Mybatis生成的SQL
    logging:
      level:
        com.kangswx.springbootmybatispagehelper.mapper: debug
    
    
  10. 利用mybatis-generator插件生成实体类,mapper和mapper对应的配置文件

  11. 实体类为

    import java.util.Date;
    
    public class User {
        private Integer id;
    
        private String username;
    
        private String password;
    
        private Integer age;
    
        private Date birthday;
    
        private String comment;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username == null ? null : username.trim();
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password == null ? null : password.trim();
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public Date getBirthday() {
            return birthday;
        }
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
    
        public String getComment() {
            return comment;
        }
    
        public void setComment(String comment) {
            this.comment = comment == null ? null : comment.trim();
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    ", age=" + age +
                    ", birthday=" + birthday +
                    ", comment='" + comment + '\'' +
                    '}';
        }
    }
    
  12. mapper接口为

    import com.kangswx.springbootmybatispagehelper.entity.User;
    import org.apache.ibatis.annotations.Mapper;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    @Repository  //手动添加
    @Mapper      //手动添加
    public interface UserMapper {
    
        int deleteByPrimaryKey(Integer id);
    
        int insert(User record);
    
        int insertSelective(User record);
    
        User selectByPrimaryKey(Integer id);
    
        List<User> findAll();  //手动添加
    
        int updateByPrimaryKeySelective(User record);
    
        int updateByPrimaryKey(User record);
    
    }
    
  13. mapper配置文件为

    <?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.kangswx.springbootmybatispagehelper.mapper.UserMapper" >
      <resultMap id="BaseResultMap" type="com.kangswx.springbootmybatispagehelper.entity.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="username" property="username" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
        <result column="birthday" property="birthday" jdbcType="TIMESTAMP" />
        <result column="comment" property="comment" jdbcType="VARCHAR" />
      </resultMap>
      <sql id="Base_Column_List" >
        id, username, password, age, birthday, comment
      </sql>
    
      <!-- 手动添加 -->
      <select id="findAll" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from t_user
      </select>
    
    
      <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select 
        <include refid="Base_Column_List" />
        from t_user
        where id = #{id,jdbcType=INTEGER}
      </select>
    
    
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from t_user
        where id = #{id,jdbcType=INTEGER}
      </delete>
      <insert id="insert" parameterType="com.kangswx.springbootmybatispagehelper.entity.User" >
        insert into t_user (id, username, password, 
          age, birthday, comment
          )
        values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
          #{age,jdbcType=INTEGER}, #{birthday,jdbcType=TIMESTAMP}, #{comment,jdbcType=VARCHAR}
          )
      </insert>
      <insert id="insertSelective" parameterType="com.kangswx.springbootmybatispagehelper.entity.User" >
        insert into t_user
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            id,
          </if>
          <if test="username != null" >
            username,
          </if>
          <if test="password != null" >
            password,
          </if>
          <if test="age != null" >
            age,
          </if>
          <if test="birthday != null" >
            birthday,
          </if>
          <if test="comment != null" >
            comment,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            #{id,jdbcType=INTEGER},
          </if>
          <if test="username != null" >
            #{username,jdbcType=VARCHAR},
          </if>
          <if test="password != null" >
            #{password,jdbcType=VARCHAR},
          </if>
          <if test="age != null" >
            #{age,jdbcType=INTEGER},
          </if>
          <if test="birthday != null" >
            #{birthday,jdbcType=TIMESTAMP},
          </if>
          <if test="comment != null" >
            #{comment,jdbcType=VARCHAR},
          </if>
        </trim>
      </insert>
      <update id="updateByPrimaryKeySelective" parameterType="com.kangswx.springbootmybatispagehelper.entity.User" >
        update t_user
        <set >
          <if test="username != null" >
            username = #{username,jdbcType=VARCHAR},
          </if>
          <if test="password != null" >
            password = #{password,jdbcType=VARCHAR},
          </if>
          <if test="age != null" >
            age = #{age,jdbcType=INTEGER},
          </if>
          <if test="birthday != null" >
            birthday = #{birthday,jdbcType=TIMESTAMP},
          </if>
          <if test="comment != null" >
            comment = #{comment,jdbcType=VARCHAR},
          </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="com.kangswx.springbootmybatispagehelper.entity.User" >
        update t_user
        set username = #{username,jdbcType=VARCHAR},
          password = #{password,jdbcType=VARCHAR},
          age = #{age,jdbcType=INTEGER},
          birthday = #{birthday,jdbcType=TIMESTAMP},
          comment = #{comment,jdbcType=VARCHAR}
        where id = #{id,jdbcType=INTEGER}
      </update>
    </mapper>
    
  14. 添加Service接口

    import com.kangswx.springbootmybatispagehelper.entity.User;
    
    import java.util.List;
    
    public interface UserService {
    
        List<User> findAll();
    }
    
  15. 添加Service实现类

    import com.kangswx.springbootmybatispagehelper.entity.User;
    import com.kangswx.springbootmybatispagehelper.mapper.UserMapper;
    import com.kangswx.springbootmybatispagehelper.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public List<User> findAll() {
            return userMapper.findAll();
        }
    }
    
  16. 添加Controller,并增加分页查询的方法

    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.kangswx.springbootmybatispagehelper.entity.User;
    import com.kangswx.springbootmybatispagehelper.service.UserService;
    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.RestController;
    
    import java.util.List;
    
    @RequestMapping("/api/v1/user")
    @RestController
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        /**
         * 分页查询User
         * @param pageNo
         * @param pageSize
         * @return
         */
        @GetMapping("find_page")
        public Object findPage(int pageNo, int pageSize){
            //设置分页信息
            PageHelper.startPage(pageNo, pageSize);
            List<User> users = userService.findAll();
            //生成分页信息对象
            PageInfo<User> pageInfo = new PageInfo<>(users);
            return pageInfo;
        }
    
    }
    
  17. 在启动类上面添加MapperScan注解

    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @MapperScan(basePackages ="com.kangswx.springbootmybatispagehelper.mapper")
    @SpringBootApplication
    public class SpringbootMybatisPagehelperApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringbootMybatisPagehelperApplication.class, args);
        }
    
    }
    
  18. 测试分页查询的结果

  19. 至此分页的功能已实现,上面所有的代码详见 SpringBoot整合Mybatis和PageHelper实现分页查询

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值