MyBatis-Plus的使用以及注意事项

MyBatis-Plus官网

同学,在使用MyBatis-plus之前,记住一句话:单表查询使用MyBatis-Plus,多表查询使用MyBatis。
因为,这样做,才能使代码更加简单,以及帮助自己快速开发。

MyBatis-Plus的使用

依赖

我这里使用的版本是
<mybatis-plus.version>3.2.0</mybatis-plus.version>

<!--            mybatis-plus-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis-plus.version}</version>
</dependency>

一张用户表

/*
 Navicat Premium Data Transfer

 Source Server         : 200
 Source Server Type    : MySQL
 Source Server Version : 80016
 Source Host           : 192.168.153.200:3306
 Source Schema         : uc

 Target Server Type    : MySQL
 Target Server Version : 80016
 File Encoding         : 65001

 Date: 29/12/2021 16:12:04
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uuid` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `image_path` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `create_date` timestamp NOT NULL,
  `update_date` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `is_deleted` tinyint(1) NULL DEFAULT 1 COMMENT '逻辑删除位,1表示可用,0表示删除',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

Java用户实体类

package cn.ant.uc.entity.po;

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @Version 1.0
 * @Author:lss
 * @Date:2021/11/5
 * @Content:
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {

//自增id
    @TableId(value = "id",type = IdType.AUTO)
    private Integer id;

    @TableField(value = "uuid")
    private String uuid;

    @TableField(value = "username")
    private String username;

    @TableField(value = "password")
    private String password;

    @TableField("image_path")
    private String imagePath;

    @TableField(value = "create_date",fill = FieldFill.INSERT)
    private Date createDate;

    @TableField(value = "update_date",fill = FieldFill.UPDATE)
    private Date updateDate;

//逻辑删除
    @TableLogic
    private Boolean isDeleted;
}

Mybati-plus的配置

mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml
  type-aliases-package: cn.ant.*.entity.*
  global-config:
    db-config:
      id-type: auto  #id自增
      logic-delete-value: 0 #逻辑删除,设置为0
      logic-not-delete-value: 1 #不删除,设置为1
    banner: false
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    call-setters-on-nulls: true
    jdbc-type-for-null: 'null'

注意事项

注意1:正常情况下,如上面的配置,就可以使用mybatis-plus了。
但是,细心的同学会发现上面的实体类,@TableField注解标记时间字段(createDate和updateDate)的时候,配置了fill = FieldFill.INSERT和fill = FieldFill.UPDATE。如果想要这样的配置生效,还需要写一个mybatis-plus的自动填充配置类。

注意2:如果想使用mybatis-plus的分页方法(如selectPage等),还需要配置一个分页插件配置类。否则,mybatis-plus分页方法不生效。

mybatis-plus自动填充配置类

package cn.ant.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * 自动填充
 */
@Configuration
public class MybatisPlusFieldFillConfigure implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setInsertFieldValByName("createDate",new Date(),metaObject);
        this.setUpdateFieldValByName("updateDate",new Date(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setUpdateFieldValByName("updateDate",new Date(),metaObject);
    }
}

分页插件配置类

使用该配置类之前,使用mybatis-plus的selectPage方法,
它的sql是:
SELECT id,update_date,password,is_deleted,image_path,uuid,create_date,username FROM user WHERE is_deleted=1

使用该配置类之后,使用mybatis-plus的selectPage方法,
它的sql是:
SELECT id,update_date,password,is_deleted,image_path,uuid,create_date,username FROM user WHERE is_deleted=1 LIMIT 0,10

package cn.ant.common.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * mybatis-plus分页插件
 */
@Configuration
public class MyBatisPlusPageInterceptor {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        //优化处理类
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
}

mybatis-plus的基本使用

mapper只需要集成mybatisPlus的BaseMapper即可,泛型类是与数据表对应的实体类,如下:

package cn.ant.uc.mapper;

import cn.ant.uc.entity.po.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;

/**
 * @Version 1.0
 * @Author:lss
 * @Date:2021/11/5
 * @Content:
 */
@Repository
public interface UserManagementMapper extends BaseMapper<User> {
}

MyBatis-Plus的CRUD

DTO类

dto是前后端交互的实体类

package cn.ant.uc.entity.dto;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "用户DTO")
public class UserDTO implements Serializable {

    @ApiModelProperty(value = "用户id")
    private Integer id;

    @ApiModelProperty(value = "用户名")
    private String username;

    @ApiModelProperty(value = "用户密码")
    private String password;

    @ApiModelProperty(value = "t头像路径")
    private String imagePath;

    @ApiModelProperty(value = "当前页索引值,默认1")
    private Integer pageIndex = 1;

    @ApiModelProperty(value = "每一页大小,默认10")
    private Integer pageSize = 10;

    @ApiModelProperty(value = "排序标记,默认true升序")
    private Boolean orderByFlag = true;
}

接口

 /**
     * 添加用户
     * @param userDTO
     * @return
     */
    public Object addUser(UserDTO userDTO);

    /**
     * 编辑用户
     * @param userDTO
     * @return
     */
    public Object editUser(UserDTO userDTO);

    /**
     * 分页查询用户
     * @param userDTO
     * @return
     */
    public Object queryUser(UserDTO userDTO);

    /**
     * 删除用户
     * @param userIdList
     * @return
     */
    public Object deleteUser(List<Integer> userIdList);

接口实现类

 @Override
    public Object addUser(UserDTO userDTO) {
        //复制对象值
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        //密码加密
        user.setPassword(SecureUtil.md5(userDTO.getPassword()));
        //生成UUId
        user.setUuid(UUID.randomUUID().toString());
        //添加数据
        Integer insert = userManagementMapper.insert(user);
        return insert;
    }

    @Override
    public Object editUser(UserDTO userDTO) {
        //构建更新条件以及字段
        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new UpdateWrapper<User>().lambda();
        //用户名不为空
        if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getUsername())) {
            userLambdaUpdateWrapper.set(User::getUsername, userDTO.getUsername());
        }
        //密码不为空
        if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getPassword())) {
            userLambdaUpdateWrapper.set(User::getPassword, userDTO.getPassword());
        }
        //头像路径不为空
        if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getImagePath())) {
            userLambdaUpdateWrapper.set(User::getImagePath, userDTO.getImagePath());
        }
        //选择条件
        userLambdaUpdateWrapper.eq(User::getId, userDTO.getId());
        int update = userManagementMapper.update(null, userLambdaUpdateWrapper);
        return update;
    }

    @Override
    public Object queryUser(UserDTO userDTO) {
        //构造查询条件
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new QueryWrapper<User>().lambda();
        //用户名不为空
        if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getUsername())) {
            userLambdaQueryWrapper.like(User::getUsername, userDTO.getUsername());
        }
        //密码不为空
        if (!Objects.isNull(userDTO) && StrUtil.isNotBlank(userDTO.getPassword())) {
            userLambdaQueryWrapper.like(User::getPassword, userDTO.getPassword());
        }
        //Id
        if (!Objects.isNull(userDTO) && !Objects.isNull(userDTO.getId())) {
            userLambdaQueryWrapper.like(User::getId, userDTO.getId());
        }
        //分页查询
        Page<User> userPage = new Page<>();
        userPage.setCurrent(userDTO.getPageIndex());
        userPage.setSize(userDTO.getPageSize());
        IPage<User> userIPage = userManagementMapper.selectPage(userPage, userLambdaQueryWrapper);
        //密码防止泄露
        ArrayList<User> users = new ArrayList<>();
        List<User> userIPageRecords = userIPage.getRecords();
        for (User userIPageRecord : userIPageRecords) {
            String password = DesensitizedUtil.password(userIPageRecord.getPassword());
            userIPageRecord.setPassword(password);
            users.add(userIPageRecord);
        }
        return users;
    }

    @Override
    public Object deleteUser(List<Integer> userIdList) {
        return userManagementMapper.deleteBatchIds(userIdList);
    }

好了,myabtis-plus的基本使用就是这样啦,我这里并没有详细介绍Mybatis-Plus的每个方法的使用,如果需要了解更多可以自行百度或者持续关注,我后面再更新。还有就是实际开发中,也差不多是这样使用。如果,在实际开发中,遇到多表查询,你要好不犹如的写上mybatis的xml配置,默默的去写sql吧。

上一篇:Ajax替代Form表单提交 重定向方法


下一篇:springmvc采用@ResponseBody注解返回中文时出现乱码问题分析和解决