First acquaintance with Mybatis-Plus

Mybatis-plus

Mybatis-plus is not official, but the official website extended by others

Moreover, it was developed by Chinese, so it is easy to read the documents. You can check the official website for the following content, and there are more detailed answers.

(In personal exercises, version, which is the optimistic lock, will not work. If you solve it later, come back and change it)

Environment configuration

Because mybatis-plus is the operation of the database, we need to configure the following mysql environment first:

CREATE TABLE USER(
id INT NOT NULL,
NAME VARCHAR(20) DEFAULT NULL
)

Then add some data to it.

Then use it with Springboot, so the springboot web scene is introduced.

Pom.xml environment configuration

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <dependencies>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

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

        <!--springboot web环境-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

spring configuration file

Setting of mysql configuration file properties (application.properties):

spring.datasource.username=root
spring.datasource.password=xxxxxx
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

test

After configuring the above, you can perform basic tests.

First, you can create a pojo class corresponding to the database table:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
}

Like Mybatis, you also need to create a Mapper interface, but the difference is that this interface inherits BaseMapper, which completes the most basic methods.

@Mapper
public interface UserMapper extends BaseMapper<User> {

}

You can already use simple query operations like the above.

Perform table query

@Controller
public class One {
    @Autowired
    private UserMapper userMapper;

    public void hello(){
    	//null表示没有任何查询条件。所以查询全部内容
        List<User> users = userMapper.selectList(null);
        for (User user : users) {
            System.out.println(user);
        }
    }
}

Log printing

Like Mybatis, there are more detailed print logs like log4j.
Add in application.yml:

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Basic operation

insert

@Controller
public class One {
    @Autowired
    private UserMapper userMapper;

    public void insert(){
        User user = new User();
        user.setName("Kem");
        userMapper.insert(user);
    }
}

Update

Change the name value of id to Tom

public class One {
    @Autowired
    private UserMapper userMapper;

    public void update(){
        User user = new User();

        userMapper.selectById(1);
        user.setId(1);
        user.setName("Tom");
        userMapper.updateById(user);

    }
}

Inquire

Query a single user:

    public void select(){
        User user = userMapper.selectById(1);
        System.out.println(user);
    }

Query multiple users:

    public void select(){
        List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3, 4));= userMapper.selectBatchIds(Arrays.asList(1, 2, 3, 4));
        for (User user : users) {
            System.out.println(user);
        }
    }

Query by condition: map for query:

    public void selectMap(){
        Map<String, Object> map = new HashMap<>();
        map.put("name","Jack");

        List<User> users = userMapper.selectByMap(map);

        for (User user : users) {
            System.out.println(user);
        }
    }

Paging query

Configure the paging plugin:

@Configuration
public class MybatisPlusConfig {
    // 最新版
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }
}

Test code:

    public void selectPage(){
        //参数一:当前页。参数二:页面大小
        Page<User> page = new Page<>(1, 5);
        userMapper.selectPage(page,null);
        List<User> records = page.getRecords();
        for (User record : records) {
            System.out.println(record);
        }
    }

delete

Single delete:

    public void delete(){
        userMapper.deleteById(1);
    }

The usage of the deleted method is similar to that of the added method.

Tombstone

What is logical deletion: It is not removed from the database, but invalidated by a variable. delete=0 or delete=1.

This method is for administrators to view deleted records and prevent data loss, similar to a recycle bin.

Essentially an update operation, not a delete operation

Environment configuration

Add the deleted field: add

Insert picture description here


in the spring configuration file (application.properties):

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: flag  # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

Test code:

    public void delete(){
        userMapper.deleteById(1);
    }

Conditional Constructor

Set for conditions, we strongly recommend looking directly at the official website of the introduction of

    public void mWrapper(){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper
                .isNotNull("name")//查找name字段部位空的
                .ge("id",3);//查找id值大于等于3的
        List<User> users = userMapper.selectList(wrapper);

        for (User user : users) {
            System.out.println(user);
        }
    }

Create and update time fill

Time filling on the database

Insert picture description here


For columns like create_time and update_time above, when we create attributes and modify fields, timestamps are automatically filled in.

Claim:

  • Check the update option
  • Need to write in the default field: CURRENT_TIMESTAMP
  • Data type is datetime

Time filling on the code

Because the direct operation of the database is basically not allowed during development, there is time to fill in the code.

Restore the table first, that is, uncheck the default values ​​and updates.

Insert picture description here

The second is the pojo class:
add the annotation @TableField() to the pojo class A. fill means: when to fill.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private long id;
    private String name;

	//进行插入是进行填充
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;
	
	//进行更新和插入时进行填充
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
}

One thing is to write: fill strategy class:

@Component
public class MyHandler implements MetaObjectHandler {

    //插入时的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    //更新时的填充策略
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

Then you can insert and update, and then observe the changes in the fields create_time and update_time.

It should be noted that the field name of the database is: create_time. It should be createTime in java, and createTime in the filling strategy class.

Code generator

As the name implies, it directly generates classes and codes for you:
when using it, you only need to change the main ones: the name of the mapping table in the policy configuration, the url in the data source configuration, and the user name and password of the database.

public class MainClass {

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("sheng");
//        gc.setFileOverride(true);//是否覆盖
        gc.setOpen(false);//打开资源管理器(我的电脑)
        mpg.setGlobalConfig(gc);
        gc.setServiceName("%sService");//去Service的I前缀
        gc.setDateType(DateType.ONLY_DATE);//日期的类型为普通类型
//        gc.setIdType(IdType.ID_WORKER);
//        gc.setSwagger2(true);//生成swagger日志


        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("xxxxxx");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("one");
        pc.setParent("com.sheng");//在该路径下生成one包,这模块下就会生成所有代码
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);


        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user");//映射表名
        strategy.setNaming(NamingStrategy.underline_to_camel);//下划线转驼峰命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);

        strategy.setLogicDeleteFieldName("deleted");
        //自动填充配置
        TableFill  createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill  updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        List<TableFill> list=new ArrayList<>();
        list.add(createTime);
        list.add(updateTime);
        strategy.setTableFillList(list);

        //乐观锁
        strategy.setVersionFieldName("version");
        strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true);//url使用下划线命名
        mpg.setStrategy(strategy);

        mpg.execute();//执行
    }
}

If you forget how to use it, you can directly cv the above code, change the necessary configuration of the database, and see the effect.