MyBatisPlus study notes [part1]

MyBatis-Plus is an enhancement tool of MyBatis. On the basis of MyBatis, only enhancements are made without changes, and it is born to simplify development and improve efficiency.

1. Pre-work

1. Introduce dependencies.

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

2. Add the relevant configuration of the MySQL database in the application.properties configuration file.

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

Among them, the url here uses the suffix ?serverTimezone=GMT%2B8, because the jdbc driver of version 8.0 needs to add this suffix, otherwise an error will be reported when running the test case. The driver-class-name here uses com.mysql.cj.jdbc.Driver. It is recommended to use this driver in jdbc 8, otherwise there will be a WARN message when running the test case.

3. Add mapper, inherit BaseMapper and supplement generics.

@Repository
public interface UserMapper extends BaseMapper<User> {
}

/*      
@Repository Both @Mapper and @Mapper are annotations used on the dao layer, marked as the persistence layer, but there will be differences in usage
@Repository It is a spring annotation, marked as a bean, and @MapperScan needs to be configured when working with mybatis
@Mapper It is an annotation of mybatis, no additional @MapperScan scanning is required.
*/

And add mapper package scanning in the main program.

@SpringBootApplication
@MapperScan(basePackages = "com.ichuang.swz.mapper")
public class SwzApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwzApplication.class, args);
    }
}

4. Next, the unit test is carried out, the result is successfully output, and the basic configuration and quick start are completed.

@Slf4j
@SpringBootTest
class SwzApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void selectAll(){
        List<User> users = userMapper.selectList(null);
        for (User user : users) {
            log.info(user.toString());
        }
    }

}

Second, the primary key strategy

Add it in the springboot configuration file to open the mybatis log, so that you can view the sql statement automatically generated by mybatis_plus in the log information.

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

1. Insert operation

Use the insert method.

    @Test
    public void testAdd() {
        User user = new User();
        user.setName("zhangsan");
        user.setAge(30);
        user.setEmail("123@qq.com");
        int i = userMapper.insert(user);
        System.out.println(i);
    }

2. The primary key strategy of MybatisPlus

The default primary key strategy of MyBatis-Plus is: ASSIGN_ID (using the snowflake algorithm)

Snowflake Algorithm is a distributed ID generator, which can ensure the non-repetition of primary keys of different tables, and the order of primary keys of the same table. The overall sorting is based on time increment, and ID collisions will not occur in the entire distributed system. And the efficiency is higher.

valueeffect
AUTODatabase ID auto-increment
NULLDo not configure the primary key strategy, that is, follow the global, that is, the snowflake algorithm
INPUTUser input before insert
ASSIGN_IDSnowflake algorithm generation
ASSIGN_UUIDAssign UUID

The configuration in a single entity is as follows.

@Data
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    
    private String name;
    private Integer age;
    private String email;
}

The global configuration is as follows.

#Globally set the primary key generation strategy
mybatis-plus.global-config.db-config.id-type=auto

3. Automatic filling

1. Update operation

In the updateById method, the parameter is passed to the entire entity. The sql generated during update is automatically dynamic sql: UPDATE user SET name=? WHERE id=?

@Test
public void testUpdate() {
    User user = new User();
    user.setId(1613767658091577345L);
    user.setName("lisi");
    int i = userMapper.updateById(user);
    System.out.println(i);
}

2. Autofill

Some data is often encountered in the project, and it is filled in the same way every time, such as the record creation time, update time, etc. We can use the autofill function of MyBatis Plus to complete the assignment of these fields.

The first step is to add auto-fill annotations.

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

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

The second step is to implement the meta-object handler interface.

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //mybatis_plus performs the add operation, this method executes
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    //mybatis_plus performs the update operation, this method executes
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

The third step is unit testing.

@Test
public void testAdd() {
    User user = new User();
    user.setName("zhangsan10");
    user.setAge(18);
    user.setEmail("888@qq.com");
    int i = userMapper.insert(user);
    System.out.println(i);
}

@Test
public void testUpdate() {
    User user = new User();
    user.setId(1613776095357759489L);
    user.setName("zhangsan7");
    int i = userMapper.updateById(user);
    System.out.println(i);
}

4. Optimistic lock

When a record is to be updated, it is hoped that this record has not been updated by others, that is to say, thread-safe data updates are implemented. For example, Zhang San and Li Si modified the employee's salary at the same time, and a lost update will occur at this time.

The principle of optimistic locking
When fetching records, get the current version.
When updating, bring this version.
When performing an update, set version = newVersion where version = oldVersion , if the version is incorrect, the update will fail.

Implementation process of optimistic locking.

The first step is to add the @Version annotation.

@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;

The second step is to register the optimistic lock plugin in the configuration file.

@Configuration
@MapperScan(basePackages = "com.ichuang.swz.mapper")  //Delete the @MapperScan scanning annotation in the main class, and put it in the configuration class of mybatis_plus later
public class MybatisPlusConfig {

    /*
     * Optimistic lock plug-in, new version configuration method
     */
    @Bean
    public MybatisPlusInterceptor optimisticLockerInnerInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

The third step is to configure automatic filling.

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //mybatis_plus performs the add operation, this method executes
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("version",1,metaObject);
    }

    //mybatis_plus performs the update operation, this method executes
    @Override
    public void updateFill(MetaObject metaObject) {
        //The modification operation does not need to be configured, and the optimistic lock is completed by itself.
    }
}

The fourth step is unit testing.

@Test
public void testAdd() {
    User user = new User();
    user.setName("lisi10");
    user.setAge(25);
    user.setEmail("333@qq.com");
    int i = userMapper.insert(user);
    System.out.println(i);
}

@Test
public void testUpdate() {
    User user = userMapper.selectById(1613780561515573250L);
    user.setName("lisi7");
    user.setAge(18);
    int i = userMapper.updateById(user);
    System.out.println(i);
}

Tags: Java Mybatis MybatisPlus

Posted by petethepirate on Sat, 14 Jan 2023 05:38:08 +0300