springboot integration mybatis-plus (quick start)


Official Website Tutorial: Introduction | MyBatis-Plus (baomidou.com)

MyBatis-Plus (opens new window) (MP for short) is an  enhancement tool for MyBatis (opens new window) . On the basis of MyBatis, it only enhances and does not change. It is born to simplify development and improve efficiency.


<!--mybatis-plus--><dependency>    <groupId>com.baomidou</groupId>    <artifactId>mybatis-plus-boot-starter</artifactId>    <version>3.0.5</version></dependency><!--mysql--><dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId></dependency><!--lombok用来简化实体类--><dependency>    <groupId>org.projectlombok</groupId>    <artifactId>lombok</artifactId></dependency>


1. After introducing MyBatis-Plus, please do not introduce MyBatis and MyBatis-Spring again to avoid problems caused by version differences.

2. The introduction of lombok is to reduce the writing of a lot of repetitive codes. For example, for the preparation of getter/setter/toString methods, IDEA or eclipse need to install the lombok plug-in, and the specific installation method is Baidu.


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

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8spring.datasource.username=rootspring.datasource.password=123456 #mybatis日志,查看sql输出日志,可以不配置mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl


1. The url here uses the suffix?serverTimezone=GMT%2B8, because Spring Boot 2.1 integrates the 8.0 version of the jdbc driver, this version of the jdbc driver needs to add this suffix, otherwise the test case will report the following error: java.sql.SQLException : The server time zone value'Öйú±ê׼ʱ¼ä' is unrecognized or represents more

2. The driver-class-name here uses com.mysql.cj.jdbc.Driver. It is recommended to use this driver in jdbc 8. The previous com.mysql.jdbc.Driver has been deprecated, otherwise it will be used when running test cases. There is WARN information


Generally, we use a code generator to generate service, mapper and entity classes. Here I recommend the IDEA plug-in MyBatisCodeHelper-Pro, which can be generated with one click.

But this is a charge, but there are usually cracked versions of plug-ins or software related to programming. If you need it, you can comment first and then send me a private message. I will send you a Baidu network disk.

Auto fill

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

For example, the fields create_time, update_time in the User table

We can add annotation @TableField on the entity class

@Datapublic class User { [email protected](fill = FieldFill.INSERT)private Date createTime;//@TableField(fill = FieldFill.UPDATE)@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;}

Also create a processing class

@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler { @Overridepublic void insertFill(MetaObject metaObject) {this.setFieldValByName("createTime", new Date(), metaObject);this.setFieldValByName("updateTime", new Date(), metaObject); }@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime", new Date(), metaObject); }}

The creation time and update time can be automatically updated

Optimistic lock

When you want to update a record, hope that this record has not been updated by others, that is to say to achieve thread-safe data update

Optimistic lock implementation:

  1. When fetching the record, get the current version
  2. When updating, bring this version
  3. When performing an update, set version = newVersion where version = oldVersion
  4. If the version is wrong, the update fails

Add @Version annotation to the version field of the entity class

@[email protected](fill = FieldFill.INSERT)private Integer version;

Here we have added the above auto-fill, when inserting, the default initial value of version is 1.

@Overridepublic void insertFill(MetaObject metaObject) { ......this.setFieldValByName("version", 1, metaObject);}

Finally, configure the optimistic lock plugin in the configuration class

@[email protected] class MybatisPlusConfig {/*** 乐观锁插件*/@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor() {return new OptimisticLockerInterceptor(); }}

Special Note:

  • The only supported data types are int, Integer, long, Long, Date, Timestamp, LocalDateTime
  • In integer type newVersion = oldVersion +1
  • newVersion will be written back to the entity
  • Only support updateById(id) and update(entity, wrapper) methods
  • Under the update(entity, wrapper) method, wrapper cannot be reused!!!


MyBatisPlus comes with a paging plug-in, so you can realize the paging function with a simple configuration

Configure the paging plugin in the configuration class

/*** 分页插件*/@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}

Pagination code

Page<User> pageParam = new Page<>(current, limit);userService.page(pageParam, null);List<User> records = pageParam.getRecords();long total = pageParam.getTotal();

According to the current number of pages (current) and the number of items per page (limit), the paging data and the total number of items are queried. You can also implement conditional paging query according to the conditional constructor Wrapper.

At last

Personally, I didn’t like mybatis-plus at first. I think it allowed programmers to reduce the writing of sql. After a long time, programmers, especially junior programmers, may not even know how to write basic additions, deletions, and changes. .

But it exists because of its existence. It will make project development easier and faster, and reduce the burden of programmers. Write less and do faster, so it is still necessary to treat mybatis-plus relatively rationally.

Mybatis-plus feels that it is suitable for single-table operation, and it is better to use mybatis to write it yourself for multi-table joint checking.