spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)

搭建环境:jdk8,maven3.3.9,MySQL 5.6,mybatisplus3.0-gamma
开发工具:idea 2018.1.5
集成mybatis plus自带的分页、逻辑删除、sql性能分析插件功能、测试公共字段自动填充功能、乐观锁

走一走看一看咯

特别注意,此案例版本是3.0-gamma,若升级到3.0-RC,需修改调用方法名,如selectById()->getById,selectPage()->page()等等....另自定义MetaObjectHandler原先是抽象类,现在改成接口,需implement,而不是extend

一、通过idea构建springboot项目

1、打开idea,点击 Create New Project 按钮

spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第1张图片

2、点击 Spring Initializr 标签,选择自己安装的jdk,点击 Next
spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第2张图片

3、选择对应的项目配置,点击 next
spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第3张图片

4、选择spring boot项目依赖,一直点击 Next,直到 finish
spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第4张图片

5、等待maven构建,构建完成的项目结构如下
spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第5张图片

二、新建MySQL数据库,初始化sql

DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户名',
  `nickname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '别名',
  `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '密码',
  `role_id` int(11) DEFAULT NULL COMMENT '权限id',
  `dept_id` int(11) DEFAULT NULL COMMENT '部门id',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime DEFAULT NULL COMMENT '修改时间',
  `remark` varchar(500) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '备注',
  `deleted` int(11) DEFAULT 0 COMMENT '是否删除(0:未删除 1:已删除)',
  `update_version` int(11) DEFAULT 0 COMMENT '乐观锁',
  `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '邮件',
  `phone` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '电话',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 18 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '用户' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;

三、配置数据库及tomcat相关信息

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123456

server:
  tomcat:
    uri-encoding: UTF-8
    max-threads: 1000
    min-spare-threads: 30
  port: 8081
  servlet:
    context-path: /

四、添加mybatis plus 依赖,更换阿里镜像仓库

maven不卡的话,就不需要切换阿里仓库了。


    com.baomidou
    mybatis-plus-boot-starter
    3.0-gamma


    
        alimaven
        aliyun maven
        http://maven.aliyun.com/nexus/content/groups/public/
    

五、构建项目基本目录结构

代码结构如图所示


spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第6张图片

model

package top.shen33.yang.model.po;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;

import java.time.LocalDateTime;
import java.io.Serializable;
import java.util.Date;

/**
 * 

* 用户 *

* * @author shen * @since 2018-07-16 */ public class SysUser extends Model { /** * 主键 */ @TableId("id") private Integer id; /** * 用户名 */ @TableField("username") private String username; /** * 别名 */ @TableField("nickname") private String nickname; /** * 密码 */ @TableField("password") private String password; /** * 权限id */ @TableField("role_id") private Integer roleId; /** * 权限名称 */ @TableField(exist = false) private String roleName; /** * 部门id */ @TableField("dept_id") private Integer deptId; /** * 部门名称 */ @TableField(exist = false) private String deptName; /** * 创建时间 */ @TableField(value = "create_time",fill = FieldFill.INSERT) private Date createTime; /** * 修改时间 */ @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) private Date updateTime; /** * 备注 */ @TableField("remark") private String remark; /** * 是否删除(0:未删除 1:已删除) */ @TableField("deleted") @TableLogic private Integer deleted; /** * 邮件 */ @TableField("email") private String email; /** * 电话 */ @TableField("phone") private String phone; /** * 乐观锁 */ @Version @TableField("update_version") private Integer updateVersion; @Override protected Serializable pkVal() { return this.id; } //getter and setter 自己写 @Override public String toString() { return "SysUser{" + ", id=" + id + ", username=" + username + ", nickname=" + nickname + ", password=" + password + ", roleId=" + roleId + ", deptId=" + deptId + ", createTime=" + createTime + ", updateTime=" + updateTime + ", remark=" + remark + ", deleted=" + deleted + ", email=" + email + ", phone=" + phone + ", updateVersion=" + updateVersion + "}"; } }

mapper

package top.shen33.yang.mapper;

import top.shen33.yang.model.SysUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * 

* 用户 Mapper 接口 *

* * @author shen * @since 2018-07-16 */ public interface SysUserMapper extends BaseMapper { }

services

package top.shen33.yang.services;

import top.shen33.yang.model.SysUser;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * 

* 用户 服务类 *

* * @author shen * @since 2018-07-16 */ public interface SysUserService extends IService { }

services.impl

package top.shen33.yang.services.impl;

import top.shen33.yang.model.SysUser;
import top.shen33.yang.mapper.SysUserMapper;
import top.shen33.yang.services.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * 

* 用户 服务实现类 *

* * @author shen * @since 2018-07-16 */ @Service public class SysUserServiceImpl extends ServiceImpl implements SysUserService { }

controller

package top.shen33.yang.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import top.shen33.yang.model.SysUser;
import top.shen33.yang.services.SysUserService;

/**
 * 

* 用户 前端控制器 *

* * @author shen * @since 2018-07-16 */ @Controller @RequestMapping("/sysUser") public class SysUserController { @Autowired private SysUserService sysUserService; @GetMapping(value = "test") public void test(){ //测试逻辑删除功能 SysUser sysUser = sysUserService.selectById(1); //测试分页 IPage sysUserIPage = sysUserService.selectPage( new Page(1, 10), new QueryWrapper<>()); //测试公共字段自动填充 SysUser sysUser1 = new SysUser(); sysUser1.setUsername("shen"); sysUser1.setNickname("shen"); sysUser1.setPassword("shen"); sysUserService.insert(sysUser1); //测试乐观锁 SysUser sysUser2 = new SysUser(); sysUser2.setId(19); sysUser2.setUsername("shen2"); sysUser2.setNickname("shen2"); sysUser2.setPassword("shen2"); sysUser2.setUpdateVersion(1); sysUserService.updateById(sysUser2); } }

六、配置mybatis plus config

配置mybatis plus自带的分页、逻辑删除、sql性能分析插件功能、测试公共字段自动填充功能、乐观锁

  1. MybatisPlusConfig 文件配置
package top.shen33.yang.core.config;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@MapperScan("top.shen33.yang.mapper")//这个注解,作用相当于下面的@Bean MapperScannerConfigurer,2者配置1份即可
public class MybatisPlusConfig {
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * sql注入器  逻辑删除插件
     * @return
     */
    @Bean
    public ISqlInjector iSqlInjector(){
        return new LogicSqlInjector();
    }

    /**
     * sql性能分析插件,输出sql语句及所需时间
     * @return
     */
    @Bean
    @Profile({"dev","test"})// 设置 dev test 环境开启
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
    /**
     * 乐观锁插件
     * @return
     */
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }

}
  1. 配置文件配置
#mybatis plus
mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: top.shen33.yang.model.po
  #typeEnumsPackage: com.baomidou.springboot.entity.enums
  global-config:
    #刷新mapper 调试神器
    db-config:
      #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
      id-type: AUTO
      #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
      field-strategy: not_empty
      #驼峰下划线转换
      column-underline: true
      #数据库大写下划线转换
      #capital-mode: true
      #逻辑删除配置
      logic-delete-value: 1
      logic-not-delete-value: 0
      db-type: mysql
    refresh: true
      #自定义填充策略接口实现
      #meta-object-handler: com.baomidou.springboot.xxx
      #自定义SQL注入器
  #sql-injector: com.baomidou.mybatisplus.extension.injector.LogicSqlInjector
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
  1. MetaObjectHandlerConfig 文件配置
package top.shen33.yang.core.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 配置公共字段自动填充功能  @TableField(..fill = FieldFill.INSERT)
 * 特别注意,3.0-gamma之前的版本 MetaObjectHandler 是抽象类
 * 3.0-RC之后的版本MetaObjectHandler 是接口
 */

@Component
public class MetaObjectHandlerConfig extends MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {

        Object createTime = getFieldValByName("createTime", metaObject);
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if (createTime == null)
            setFieldValByName("createTime",new Date(), metaObject);//mybatis-plus版本2.0.9+
        if (updateTime == null)
            setFieldValByName("updateTime",new Date(), metaObject);//mybatis-plus版本2.0.9+
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if (updateTime == null) {
            setFieldValByName("updateTime", new Date(), metaObject);//mybatis-plus版本2.0.9+
        }
    }
}

七、启动程序,运行http://localhost:8081/sysUser/test,结果如下

7.1逻辑删除功能测试 具体使用查看官方文档

注意:新增时sql不会新增@TableLogic的字段,建议数据库给默认值,默认是为逻辑删除中配置的logic-not-delete-value的值

spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第7张图片

7.2分页功能测试

spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第8张图片

7.3公共字段自动填充功能测试

  1. 新增


    spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第9张图片
  1. 修改


    spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第10张图片

    spring boot 2.0 框架搭建及整合mybatis plus 3.0(一)_第11张图片

7.4 乐观锁测试

八、项目地址

项目地址
写文章不易,如对您有帮助,请帮忙点下star

你可能感兴趣的:(spring boot 2.0 框架搭建及整合mybatis plus 3.0(一))