简单介绍一下mybatis-plus

mybatis-plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网。
mybatis-plus有很多特性,这篇文章仅仅讨论mybatis-plus插入数据时候某些数据的自动赋值

基本版本

(关于版本匹配问题可以百度或者去官网查看)

<java.version>1.8</java.version>
<mybatis.plus.version>3.3.1</mybatis.plus.version>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>

BaseEntity.java

public class BaseEntity implements Serializable {
    /**
     * 创建时间
     */
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    /**
     * 更新时间
     */
//    @TableField(fill = FieldFill.UPDATE)
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

    /**
     * 版本号
     */
    @Version
    @TableField(fill = FieldFill.INSERT)
    private Integer version;
    /**
     * 逻辑删除
     */
    @TableLogic
    @TableField(fill = FieldFill.INSERT)
    private Boolean disable;
}

UserEntity.java

public class UserEntity extends BaseEntity implements Serializable {
    @TableId(type= IdType.ASSIGN_UUID)
    private String id;
    private String userName;
    private String password;
}

UserMapper.java

public interface UserMapper extends BaseMapper<UserEntity> {
}

UserService.java

public interface UserService {
    UserEntity insert(YnetVO<UserVO, Object> vo);


    String sayHello();

    List<UserEntity> all();

    Boolean delete(String id);

    UserEntity update(YnetVO<UserVO, Object> vo);
}

UserServiceImpl.java

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Override
    public UserEntity insert(YnetVO<UserVO, Object> vo) {
        UserEntity entity = new UserEntity();
        BeanUtils.copyProperties(vo.getBody(),entity);
        if(1 == baseMapper.insert(entity)){
            return entity;
        }
        return null;
    }

    @Override
    public String sayHello() {
        return "hello world!!!";
    }

    @Override
    public List<UserEntity> all() {

        return baseMapper.selectList(null);
    }

    @Override
    public Boolean delete(String id) {
        return 1==baseMapper.delete(new QueryWrapper<UserEntity>().eq("id",id));
    }

    @Override
    public UserEntity update(YnetVO<UserVO, Object> vo) {
        UserEntity entity=new UserEntity();
        BeanUtils.copyProperties(vo.getBody(),entity);
        if (1==baseMapper.update(entity,new QueryWrapper<UserEntity>()
                .eq("user_name",vo.getBody().getUserName()))){
            return entity;
        }
        return null;
    }
}

MybatisPlusConfig.java

@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {
    /**
     * 分页插件
     *
     * @return 分页拦截器
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
        // paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

    /**
     * 乐观锁插件
     *
     * @return 乐观锁拦截器
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}
核心

MyMetaObjectHandler.java

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 插入元对象字段填充(用于插入时对公共字段的填充)
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("createTime")) {
            Object createTime = metaObject.getValue("createTime");
            if (createTime == null) {
                this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
            }
        }
        if (metaObject.hasGetter("updateTime")) {
            Object updateTime = metaObject.getValue("updateTime");
            if (updateTime == null) {
                this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
            }
        }
//        if (LoginUserUtils.loginUser() != null) {
//            this.strictInsertFill(metaObject, "creator", String.class, LoginUserUtils.loginUserId());
//        }
        this.strictInsertFill(metaObject, "version", Integer.class, 1);
        this.strictInsertFill(metaObject, "disable", Boolean.class, false);
    }

    /**
     * 更新元对象字段填充(用于更新时对公共字段的填充)
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
//        if (LoginUserUtils.loginUser() != null) {
//            this.strictUpdateFill(metaObject, "updator", String.class, LoginUserUtils.loginUserId());
//        }
    }
}

Sql

DROP TABLE IF EXISTS `user_info`;

CREATE TABLE `user_info` (
  `id` varchar(64) NOT NULL,
  `user_name` varchar(64) DEFAULT NULL,
  `password` varchar(64) DEFAULT NULL,
  `create_time` timestamp NULL DEFAULT NULL,
  `update_time` timestamp NULL DEFAULT NULL,
  `disable` tinyint(1) DEFAULT NULL,
  `version` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

调用插入
在这里插入图片描述

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐