SpringBoot系列:MybatisPlus的入门级使用教程(中)

作者平台:

| CSDN:https://blog.csdn.net/qq_41153943

| 掘金:https://juejin.cn/user/651387938290686

| 知乎:https://www.zhihu.com/people/1024-paper-96

| GitHub:https://github.com/JiangXia-1024?tab=repositories

| 微信公众号:1024笔记

本文大约5834字,预计阅读时长15分钟

前言

距离上一篇文章已经过去一个多礼拜了!今天分享的是MP入门使用教程的中篇部分!

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。有了它我们不再需要写多余的配置文件或者方法。上一篇文章SpringBoot系列:MybatisPlus的入门级使用教程(上)简单介绍了MyBatis-Plus以及它的一些基础的CRUD,今天这篇文章继续学习MyBatis-Plus。

正文

本文是在上一篇文章的基础之上进行拓展,所以如果有不清楚的可以先参考上一篇文章SpringBoot系列:MybatisPlus的入门级使用教程(上),源码地址会放在最后。

MyBatis-Plus给我们提供了自动填充的功能。一般时候如果我们更新或者插入数据的时候有更新时间或者创建时间,我们可以通过给这两个字段赋值的形式进行更新。比如:

user.setCreateTime("2022-02-12");
user.setUpdateTime("2022-02-12");

但是如果使用MyBatis-Plus则不需要这样操作。使用MyBatis-Plus只需要在实体类上添加@TableField注解,然后赋值类型。该注解用于标识非主键的字段,将数据库列与 JavaBean 中的属性进行映射。其源码如下:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface TableField {
    String value() default "";
    String el() default "";
    boolean exist() default true;
    
    String condition() default "";
    String update() default "";
    FieldStrategy strategy() default FieldStrategy.DEFAULT;
    FieldFill fill() default FieldFill.DEFAULT;
    boolean select() default true;
}

There is a FieldFill attribute, which indicates the field filling strategy. FieldFill is an enumeration class, and the source code of the specific field filling strategy is listed as follows:

public enum FieldFill {
    DEFAULT, //默认不处理
    INSERT, //插入填充字段
    UPDATE, //更新填充字段
    INSERT_UPDATE; //插入和更新填充字段

    private FieldFill() {
    }
}

So it can be used like this on the corresponding field of the entity class:

    //create_time
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
    //update_time
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;

Doing this is not enough to achieve automatic filling. It is also necessary to make a metadata processing strategy and declare an automatic filling processing class:

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //使用mp的添加操作,则执行这个方法
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    //使用mp的更新操作,则这个方法执行
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

Test Methods:

//测试插入数据自动填充
    @Test
    public void insertUser1(){
        User user = new User();
        user.setName("艾希2");
        user.setAge(33);
        user.setEmail("[email protected]");
        int insertCount = userMapper.insert(user);
        System.out.println("插入数据的条数是:"+insertCount);
    }

    //更新
    @Test
    public void updateUser(){
        User user = new User();
        user.setId(1l);
        user.setAge(99);
        int updateCount = userMapper.updateById(user);
        System.out.println(updateCount);
    }

As a result, the update_time field is updated when updating, and the create_time and update_time fields are updated when inserting:

图片

MP provides rich query interface processing. For example, if you need to query data based on an id, you can use:

@Test
public void testSelectById(){
    User user = userMapper.selectById(1L);
    System.out.println(user);
}

If you need to batch query through multiple ids, you can write like this:

@Test
public void testSelectBatchIds(){
    List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
    users.forEach(System.out::println);
}

You can also encapsulate query conditions through a map object:

 //根据条件查询
    @Test
    public void selectuserbymap(){
        HashMap<String,Object> map = new HashMap<>();
        map.put("age",26);
        map.put("email","[email protected]");
        List<User> users = userMapper.selectByMap(map);
        System.out.println(users);
    }

Here the key in the map corresponds to the column name in the database. For example, the database user_id, the entity class is userId, then the key of the map needs to fill in user_id.

To query all data, you can write like this:

 @Test
 public void findAll(){
        List<User> users = userMapper.selectList(null);
        System.out.println(users);
  }

It can be found that the parameter behind the selectlist method here passes a null. This is because MP provides a conditional constructor queryWrapper that encapsulates query conditions. The conditions are encapsulated through this class, and then the encapsulated object is passed into the query method. MP Conditional processing will be performed automatically, if the parameter is null, there is no condition. This is also the part with more MP content, which will be placed in the next article.

The deletion method provided by MP is very similar to the query, which can be queried through simple id query, multiple id query and condition combination query, such as:

 //根据id删除操作
    @Test
    public void deletebyid(){
        int result = userMapper.deleteById(1489438016182263810l);
        System.out.println(result);
    }

    //根据id批量删除操作
    @Test
    public void deletebybatchid(){
        int result = userMapper.deleteBatchIds(Arrays.asList(1489160121316552706l,1488850305184493570l));
        System.out.println(result);
    }

    //按照条件删除
    @Test
    public void deletebymap(){
        HashMap<String,Object> map = new HashMap<>();
        map.put("age",44);
        map.put("email","[email protected]");
        int result = userMapper.deleteByMap(map);
        System.out.println(result);
    }

The above deletions are physical deletions, that is, the corresponding data will be deleted from the database, and the deleted data cannot be queried afterwards, which is a real deletion.

MP also provides a method of logical deletion. This is by adding a field in the database to indicate whether it is a logical deletion, such as the deleted field. Then add the @TableLogic annotation to the entity class

    //逻辑删除
    @TableLogic
    @TableField(fill = FieldFill.INSERT)
    private Integer deleted

The @TableLogic annotation indicates logical deletion, and the source code is as follows:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface TableLogic {
    String value() default "";

    String delval() default "";
}

Annotation parameters: value = undeleted value, the default value is 0

 delval = 删除后的值,默认值为1

It can be used as in the above code, or it can be used like this

@TableLogic(value=“原值”,delval=“修改值”)

You can also add application.properties to the configuration and set the default value. If the default value is the same as the default value of mp, you can omit it:

#mp逻辑删除相关配置
mybatis-plus.global-config.db-config.logic-delete-value=1;
mybatis-plus.global-config.db-config.logic-not-delete-value=0;

It is also possible to add the default value of deleted insert in the meta object processor interface, then the default value of the field will be updated by inserting the default value.

this.setFieldValByName("deleted", 0, metaObject);

最后这里需要使用注入ISqlInjector组件,该组件内返回的是LogicSqlInjector。

@Bean
public ISqlInjector sqlInjector() {
    return new LogicSqlInjector();
}

LogicSqlInjector源码如下:

public class LogicSqlInjector extends AbstractSqlInjector {
    public LogicSqlInjector() {
    }

    public List<AbstractMethod> getMethodList() {
        return (List)Stream.of(new Insert(), new LogicDelete(), new LogicDeleteByMap(), new LogicDeleteById(), new LogicDeleteBatchByIds(), new LogicUpdate(), new LogicUpdateById(), new LogicSelectById(), new LogicSelectBatchByIds(), new LogicSelectByMap(), new LogicSelectOne(), new LogicSelectCount(), new LogicSelectMaps(), new LogicSelectMapsPage(), new LogicSelectObjs(), new LogicSelectList(), new LogicSelectPage()).collect(Collectors.toList());
    }
}

提供了很多逻辑删除(LogicDelete)的方法。测试逻辑删除:

//测试 逻辑删除:先插入一条数据,自动填充deleted为0,删除后字段变成1,执行findall方法会排除delete等于1的数据
    @Test
    public void testLogicDelete() {
        int result = userMapper.deleteById(2l);
        System.out.println(result);
    }

图片

id为2的之前deleted字段的值为0,现在更改了为1。则表示逻辑删除成功。逻辑删除之后,数据库中仍然保留了该条数据,但是默认查询不到该条数据了。因为查询语句后面默认是加了条件 WHERE deleted=0。

总结

以上就是关于mybatisplus的一些简单的介绍以及关于查找和插入的简单使用,篇幅有限后续将继续更新。更多关于mybatisplus的内容可以参考以下内容:

mybatisplus源码地址:
https://gitcode.net/mirrors/baomidou/mybatis-plus?utm_source=csdn_github_accelerator
MP官网地址:
https://baomidou.com/pages/24112f/

相关推荐

Guess you like

Origin blog.csdn.net/qq_41153943/article/details/124979617