上一篇 SpringBoot集成Mysql、Mybatis、Mybatis-Plus,实现增删改查

一、前言

Mybatis-Plus是Mybatis增强工具,除了封装了基本的增删改查之外,还提供了一些好玩的东西,如逻辑删除配置和自动填入默认值。

  • 记住:所有的删除都是逻辑删除,所以数据库必须有一个字段,一般是 is_deleted 0-表示未删除 1-表示已删除

二、sql语句

CREATE TABLE `user_info` (
	`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '用户id',
	`username` VARCHAR(20) NOT NULL DEFAULT '' COMMENT '用户名' COLLATE 'utf8mb4_general_ci',
	`password` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '密码' COLLATE 'utf8mb4_general_ci',
	`is_deleted` INT(2) NOT NULL DEFAULT '0' COMMENT '是否删除 0-未删除 1-已删除',
	`create_time` DATETIME NOT NULL COMMENT '创建时间',
	`update_time` DATETIME NOT NULL COMMENT '更新时间',
	PRIMARY KEY (`id`) USING BTREE
)
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB;

用户表,主要就以下字段:

  • id 用户id 主键
  • username 用户名
  • password 密码
  • is_deleted 是否删除 0-未删除 1-已删除
  • create_time 创建时间
  • update_time 更新时间

三、逻辑删除配置

application.properties

# 应用名称
spring.application.name=spring-boot-demo
server.port=8888
# 数据库相关
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=0320
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# mybatis相关
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
# mybatis-plus相关
# 逻辑删除
mybatis-plus.global-config.db-config.logic-delete-field=isDeleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

配置逻辑删除字段 isDeleted(注意是类成员变量而不是数据库字段is_deleted)
已删除的值:1 未删除的值:0

# 逻辑删除
mybatis-plus.global-config.db-config.logic-delete-field=isDeleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

这样调用Mybatis-Plus的删除方法会去更改is_deleted为1,查询方法只查询is_deleted = 0的数据。

四、自动填入默认值

MyMetaObjectHandler 类

package com.llh.springbootdemo.config;

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

import java.time.LocalDateTime;

/**
 * @author llh
 */
public class MyMetaObjectHandler implements MetaObjectHandler {
    private static final String CREATE_TIME = "createTime";
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 自动填入创建时间
        if (metaObject.hasGetter(CREATE_TIME)) {
            this.fillStrategy(metaObject, CREATE_TIME, LocalDateTime.now());
        }

        // 自动填入更新时间
        if (metaObject.hasGetter(UPDATE_TIME)) {
            this.fillStrategy(metaObject, UPDATE_TIME, LocalDateTime.now());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 自动填入更新时间
        if (metaObject.hasGetter(UPDATE_TIME)) {
            this.fillStrategy(metaObject, UPDATE_TIME, LocalDateTime.now());
        }
    }
}
  • insertFill 插入数据的时候数据库字段create_time update_time自动填入当前时间
  • updateFill 更新数据的时候数据库字段update_time自动填入当前时间

MyConfiguration 类

package com.llh.springbootdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author llh
 */
@Configuration
public class MyConfiguration {
    @Bean
    public MyMetaObjectHandler myMetaObjectHandler() {
        return new MyMetaObjectHandler();
    }
}
  • 配置类,自动注入Bean。

在类成员变量加上注解@TableField(fill = FieldFill.INSERT)@TableField(fill = FieldFill.INSERT_UPDATE),表示需要自动填入。

@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;

UserInfo 类

package com.llh.springbootdemo.entity;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;

import java.time.LocalDateTime;

/**
 * @author llh
 */
public class UserInfo {
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    private String username;

    private String password;

    private Integer isDeleted;

    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(Integer isDeleted) {
        this.isDeleted = isDeleted;
    }

    public LocalDateTime getCreateTime() {
        return createTime;
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
    }

    public LocalDateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(LocalDateTime updateTime) {
        this.updateTime = updateTime;
    }

    @Override
    public String toString() {
        return "UserInfo{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", isDeleted=" + isDeleted +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                '}';
    }
}

  • 然后插入操作就可以自动填入默认值了。

五、结语

同步微信公众号:小虎哥的技术博客

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐