SpringBoot实战项目学习(10)——集成Mybatis的通用Mapper插件和PageHelper分页插件

文章目录

  • 项目结构
  • pom.xml
  • application.yml
  • UserMapper
  • UserMapperTest

使用SpringBoot集成Mybatis、通用Mapper插件和分页助手插件

基于GitHub项目xkcoding/**spring-boot-demo**进行学习

项目地址:https://github.com/xkcoding/spring-boot-demo

项目结构

SpringBoot实战项目学习(10)——集成Mybatis的通用Mapper插件和PageHelper分页插件_第1张图片

pom.xml

  • 需要引入通用Mapper插件依赖(其中包括Mybatis依赖)mapper-spring-boot-starter和分页插件依赖pagehelper-spring-boot-starter

<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.0modelVersion>

    <artifactId>spring-boot-demo-orm-mybatis-mapper-pageartifactId>
    <version>1.0.0-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>spring-boot-demo-orm-mybatis-mapper-pagename>
    <description>Demo project for Spring Bootdescription>

    <parent>
        <groupId>com.xkcodinggroupId>
        <artifactId>spring-boot-demoartifactId>
        <version>1.0.0-SNAPSHOTversion>
    parent>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>1.8java.version>
        <mybatis.mapper.version>2.0.4mybatis.mapper.version>
        <mybatis.pagehelper.version>1.2.9mybatis.pagehelper.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>

        
        <dependency>
            <groupId>tk.mybatisgroupId>
            <artifactId>mapper-spring-boot-starterartifactId>
            <version>${mybatis.mapper.version}version>
        dependency>

        
        <dependency>
            <groupId>com.github.pagehelpergroupId>
            <artifactId>pagehelper-spring-boot-starterartifactId>
            <version>${mybatis.pagehelper.version}version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
        dependency>

        <dependency>
            <groupId>com.google.guavagroupId>
            <artifactId>guavaartifactId>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
    dependencies>

    <build>
        <finalName>spring-boot-demo-orm-mybatis-mapper-pagefinalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-plugin<artifactId>
            plugin>
        plugins>
    build>

project>

application.yml

  • 对Mybatis、mapper、pagehelper的相关参数进行配置
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
    username: root
    password: jkl555444
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource
    initialization-mode: always
    continue-on-error: true
    schema:
    - "classpath:db/schema.sql"
    data:
    - "classpath:db/data.sql"
    hikari:
      minimum-idle: 5
      connection-test-query: SELECT 1 FROM DUAL
      maximum-pool-size: 20
      auto-commit: true
      idle-timeout: 30000
      pool-name: SpringBootDemoHikariCP
      max-lifetime: 60000
      connection-timeout: 30000
logging:
  level:
    com.xkcoding: debug
    com.xkcoding.orm.mybatis.MapperAndPage.mapper: trace
mybatis:
  configuration:
    # 下划线转驼峰
    map-underscore-to-camel-case: true
  mapper-locations: classpath:mappers/*.xml
  type-aliases-package: com.xkcoding.orm.mybatis.MapperAndPage.entity
mapper:
  mappers:
  - tk.mybatis.mapper.common.Mapper
  not-empty: true
  style: camelhump
  wrap-keyword: "`{0}`"
  safe-delete: true
  safe-update: true
  identity: MYSQL
pagehelper:
  auto-dialect: true
  helper-dialect: mysql
  reasonable: true
  params: count=countSql

UserMapper

  • UserMapper继承了Mapper, MySqlMapper,所以其有常用的CRUD方法
package com.xkcoding.orm.mybatis.MapperAndPage.mapper;

import com.xkcoding.orm.mybatis.MapperAndPage.entity.User;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

/**
 * 

* UserMapper *

* * @package: com.xkcoding.orm.mybatis.MapperAndPage.mapper * @description: UserMapper * @author: yangkai.shen * @date: Created in 2018/11/8 14:15 * @copyright: Copyright (c) 2018 * @version: V1.0 * @modified: yangkai.shen */
@Component public interface UserMapper extends Mapper<User>, MySqlMapper<User> { }

SpringBoot实战项目学习(10)——集成Mybatis的通用Mapper插件和PageHelper分页插件_第2张图片

UserMapperTest

  • UserMapperTest对Mapper常用方法和分页插件进行方法测试
package com.xkcoding.orm.mybatis.MapperAndPage.mapper;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xkcoding.orm.mybatis.MapperAndPage.SpringBootDemoOrmMybatisMapperPageApplicationTests;
import com.xkcoding.orm.mybatis.MapperAndPage.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 

* UserMapper 测试 *

* * @package: com.xkcoding.orm.mybatis.MapperAndPage.mapper * @description: UserMapper 测试 * @author: yangkai.shen * @date: Created in 2018/11/8 14:25 * @copyright: Copyright (c) 2018 * @version: V1.0 * @modified: yangkai.shen */
@Slf4j public class UserMapperTest extends SpringBootDemoOrmMybatisMapperPageApplicationTests { @Autowired private UserMapper userMapper; /** * 测试通用Mapper - 保存 */ @Test public void testInsert() { String salt = IdUtil.fastSimpleUUID(); // 使用Lombok的Builder注解实现建造者模式,设置user的相关信息 User testSave3 = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("[email protected]").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build(); userMapper.insertUseGeneratedKeys(testSave3); Assert.assertNotNull(testSave3.getId()); log.debug("【测试主键回写#testSave3.getId()】= {}", testSave3.getId()); } /** * 测试通用Mapper - 批量保存 */ @Test public void testInsertList() { List<User> userList = Lists.newArrayList(); for (int i = 4; i < 14; i++) { String salt = IdUtil.fastSimpleUUID(); User user = User.builder().name("testSave" + i).password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave" + i + "@xkcoding.com").phoneNumber("1730000000" + i).status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build(); userList.add(user); } int i = userMapper.insertList(userList); Assert.assertEquals(userList.size(), i); List<Long> ids = userList.stream().map(User::getId).collect(Collectors.toList()); log.debug("【测试主键回写#userList.ids】= {}", ids); } /** * 测试通用Mapper - 删除 */ @Test public void testDelete() { Long primaryKey = 1L; int i = userMapper.deleteByPrimaryKey(primaryKey); Assert.assertEquals(1, i); User user = userMapper.selectByPrimaryKey(primaryKey); Assert.assertNull(user); } /** * 测试通用Mapper - 更新 */ @Test public void testUpdate() { Long primaryKey = 1L; User user = userMapper.selectByPrimaryKey(primaryKey); user.setName("通用Mapper名字更新"); int i = userMapper.updateByPrimaryKeySelective(user); Assert.assertEquals(1, i); User update = userMapper.selectByPrimaryKey(primaryKey); Assert.assertNotNull(update); Assert.assertEquals("通用Mapper名字更新", update.getName()); log.debug("【update】= {}", update); } /** * 测试通用Mapper - 查询单个 */ @Test public void testQueryOne(){ User user = userMapper.selectByPrimaryKey(1L); Assert.assertNotNull(user); log.debug("【user】= {}", user); } /** * 测试通用Mapper - 查询全部 */ @Test public void testQueryAll() { List<User> users = userMapper.selectAll(); Assert.assertTrue(CollUtil.isNotEmpty(users)); log.debug("【users】= {}", users); } /** * 测试分页助手 - 分页排序查询 */ @Test public void testQueryByPageAndSort() { initData(); int currentPage = 1; int pageSize = 5; String orderBy = "id desc"; int count = userMapper.selectCount(null); PageHelper.startPage(currentPage, pageSize, orderBy); List<User> users = userMapper.selectAll(); PageInfo<User> userPageInfo = new PageInfo<>(users); Assert.assertEquals(5, userPageInfo.getSize()); Assert.assertEquals(count, userPageInfo.getTotal()); log.debug("【userPageInfo】= {}", userPageInfo); } /** * 测试通用Mapper - 条件查询 */ @Test public void testQueryByCondition() { initData(); Example example = new Example(User.class); // 过滤 example.createCriteria().andLike("name", "%Save1%").orEqualTo("phoneNumber", "17300000001"); // 排序 example.setOrderByClause("id desc"); int count = userMapper.selectCountByExample(example); // 分页 PageHelper.startPage(1, 3); // 查询 List<User> userList = userMapper.selectByExample(example); PageInfo<User> userPageInfo = new PageInfo<>(userList); Assert.assertEquals(3, userPageInfo.getSize()); Assert.assertEquals(count, userPageInfo.getTotal()); log.debug("【userPageInfo】= {}", userPageInfo); } /** * 初始化数据 */ private void initData() { testInsertList(); } }
  • 效果:运行testQueryByCondition()方法

SpringBoot实战项目学习(10)——集成Mybatis的通用Mapper插件和PageHelper分页插件_第3张图片

你可能感兴趣的:(SpringBoot实战项目)