Improve productivity, the most complete mybatis plus explanation!

Time:2021-4-19

Hello everyone, I’m a piece of cake, a piece of cake eager to be Cai Bucai in the Internet industry. Soft or hard, praise is soft, white whoring is just!Ghost ~ remember to give me a third company after watching it!

Improve productivity, the most complete mybatis plus explanation!

This article mainly introducesUse of mybatisplus

If necessary, please refer to

If it helps, don’t forgetgive the thumbs-up

The official account of WeChat has been opened.A good story of a small dishIf you don’t pay attention, remember to pay attention!

If you’re repeating it every dayCRUDOfSQLIf you’re interested in theseSQLAlready impatient, so why don’t you spend some time to read this article, and then transform the existing old project, there will be harvest!

1、 What is MP

MPFull nameMybatis-PlusTo paraphrase the official explanation is to be mybatis’ best partnerJiyou. It’s in theMyBatisOn the basis of this, we only enhance and do not change, in order to simplify development and improve efficiency.

1. Three characteristics

1) Moisten things silently

Only strengthening without change, the introduction of it will not have an impact on the existing project, as smooth as silk.

2) Efficiency first

With simple configuration, single table crud operation can be performed quickly, thus saving a lot of time.

3) Rich functions

Code generation, physical paging, performance analysis and other functions are all available.

2. Support database

  • mysqlmariadboracledb2h2hsqlsqlitepostgresqlsqlserverprestoGaussFirebird
  • PhoenixclickhouseSybase ASEOceanBase, Dameng database, Xugu database, Renmin Jincang database, NANDA general database

3. Frame structure

Improve productivity, the most complete mybatis plus explanation!

To tell you the truth, as long as you open the official website, you can see the above contents, then we’ll do some practical operation first!

Improve productivity, the most complete mybatis plus explanation!

2、 MP actual combat

1. Hand touch exercise

1) Database and table preparation

SQL statement:

use test;
 CREATE TABLE `student`  (
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `dept_id` int(0) NULL DEFAULT NULL,
  `name` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  `remark` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
 ) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
 -- ----------------------------
 -- Records of student
 -- ----------------------------
 Insert into 'student' values (1,1, 'side dish','pay attention to side dish, don't get lost! ');
 Insert into 'student' values (2,2, 'Xiaoming','Study hard and make progress every day! ');

2) POM dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
 </dependency>
 <!--lombok-->
 <dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.16.16</version>
 </dependency>
 <! -- MP plug in -- >
 <dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-boot-starter</artifactId>
  <version>3.2.0</version>
 </dependency>
 <!--Mysql-->
 <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.21</version>
 </dependency>
 <! -- connection pool -- >
 <dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.2.1</version>
 </dependency>
 <!--JUNIT-->
 <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13.1</version>
 </dependency>

3) Configuration file

 spring:
  datasource:
  url: jdbc:mysql://localhost:3306/test
  username: root
  password: 123456
  driver-class-name: com.mysql.cj.jdbc.Driver

4) Entity class

 @Data
 @Builder
 @TableName("student")
 public class User {
 ​
  @TableId(type = IdType.AUTO)
  private Integer id;
 ​
  private Integer deptId;
 ​
  private String name;
 ​
  private String remark;
 }

5)Mapper

 public interface UserMapper extends BaseMapper<User> {}

6) Test class

@RunWith(SpringRunner.class)
 @SpringBootTest
 public class MapperTest {
 ​
  @Autowired
  private UserMapper userMapper;
 ​
  @Test
  public void getAll() {
  List<User> users = userMapper.selectList(null);
  users.forEach(System.out::println);
  }
 }
 /** OUTPUT:
 User (id = 1, deptid = 1, name = side dish, remark = pay attention to side dish, don't get lost! )
 User (id = 2, deptid = 1, name = Xiaoming, remark = study hard and make progress every day! )
 **/

Summary:

In the above results, we can see that all the data (two) in the database have been printed. And we didn’t see what we usually need to writemapper.xmlFile, just used itusermapperInselectList()Method, andUserMapperInheritedBaseMapperThis interface, this interface isMybatisPlusLet’s take a look at the methods provided by this interface.

2. Crud basic operation

1)insert

@Test
 public void insert() {
  //The builder pattern in Lombok is used to build objects
  User user =  User.builder (). Deptid (1). Name ("Xiaohua"). Remark ("Xiaohua love learning"). Build();
  int insertFlag = userMapper.insert(user);
  log.info (insert number of affected rows, {} | ID of Xiaohua: {}), insertflag, user.getId ());
 }
 /** OUTPUT:
 Insert the number of affected rows, 1 | Xiaohua's ID: 8
 **/

You can see that we not only insert the data, but also get the information of the inserted dataIDBut it’s worth noting thatIDAlthough it is self increasing, it is notMPdefaultID generation strategyInstead, we specify in the entity class:

Improve productivity, the most complete mybatis plus explanation!

stayMPThere are several primary key generation strategies supported in

Improve productivity, the most complete mybatis plus explanation!

Now that we have seen it@TableIdThis annotation, let’s focus on a common annotation@TableField

As we can see from the name of the annotation,@TableIdIs used to mark the primary keyIDYes, and@TableFieldIs used to mark other fields.

Improve productivity, the most complete mybatis plus explanation!

You can see that there are many values in this annotation. Here are some common values:

  • value

It is used to solve the problem of inconsistent field names and hump naming, such as attribute name in entity classremark, but the field name in the table isdescribeIt can be used at this time@TableField(value="describe")To convert. Hump conversion if hump naming is configured in the global, this place can not be written.

  • exist

For fields that do not exist in the data table, we can use@TableField(exist = false)To mark

  • condition

Used in pretreatmentWHEREEntity condition custom operation rules, for example, I configured@TableField(condition = SqlCondition.LIKE), outputSQLFor:Select table where name like concat ('%', value, '%')Of whichSqlConditionThe values are as follows:

Improve productivity, the most complete mybatis plus explanation!

  • update

Used in pretreatmentsetField custom injection, for example, I configured@TableField(update = "%s+1")Of which%sFields will be filled and outputSQLFor:Update table name set field = field + 1 where condition

  • select

It is used to constrain whether to query if we have a fieldremarkyestextIf you don’t want to query this field, you can use it@TableField(select = false)To constrain the query without querying the field

2)update

MybatisPlusThere are two kinds of update operations for

 int updateById(Param("et") T entity);
 ​
 int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
Update by ID
@Test
 public void update() {
  User user =  User.builder (). ID (3). Name ("Xiaohua"). Remark ("Xiaohua likes playing games"). Build();
  userMapper.updateById(user);
 }
 /**Update result:
 User (id = 3, deptid = 1, name = Xiaohua, remark = Xiaohua likes to play games)
 **/
Update according to conditions
@Test
 public void update() {
  UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
  updateWrapper.eq ("name", "Xiaohua"). Set ("remark", "Xiaohua likes playing chess");
  userMapper.update(null, updateWrapper);
 }
 /**Update result:
 User (id = 3, deptid = 1, name = Xiaohua, remark = Xiaohua likes playing chess)
 **/

We can also put the conditions to be updated in theUser objectInside:

@Test
 public void update() {
  UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
  updateWrapper.eq ("name", "Xiaohua");
  User user =  User.builder (). Remark ("Xiaohua love swimming"). Build();
  userMapper.update(user, updateWrapper);
 }
 /**Update result:
 User (id = 3, deptid = 1, name = Xiaohua, remark = Xiaohua love swimming)
 **/

3)delete

stayMybatisPlusThere are four ways to delete compared with update

 int deleteById(Serializable id);
 ​
 int deleteByMap(@Param("cm") Map<String, Object> columnMap);
 ​
 int delete(@Param("ew") Wrapper<T> wrapper);
 ​
 int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
Delete by ID
@Test
 public void deleteById() {
  userMapper.deleteById(3);
 }
 /**SQL statement:
 DELETE FROM student WHERE id = 3;
 **/
Delete according to map
@Test
 public void deleteByMap() {
  HashMap<String, Object> columnMap = new HashMap<>();
  columnMap.put ("name", "Xiaohua");
  columnMap.put ("remark", "Xiaohua love swimming");
  userMapper.deleteByMap(columnMap);
 }
 /**SQL statement:
 Delete from student whre name ='xiaohua 'and remark ='xiaohua loves swimming';
 **/
Delete according to wrapper
@Test
 public void delete() {
  UpdateWrapper<User> wrapper = new UpdateWrapper<>();
  wrapper.eq (Xiao Hua likes to play chess);
  userMapper.delete(wrapper);
 }
 /**SQL statement:
 Delete from student whre remark ='xiaohua likes playing chess';
 **/

according toWrapperThere is another way to delete, which is to put the entity class directly into theWrapperMedium package:

@Test
 public void delete() {
  User user =  User.builder (). Remark ("Xiaohua likes playing chess"). Build();
  UpdateWrapper<User> wrapper = new UpdateWrapper<>(user);
  userMapper.delete(wrapper);
 }
 /**SQL statement:
 Delete from student whre remark ='xiaohua likes playing chess';
 **/
Batch delete by ID
@Test
 public void deleteBatchIds() {
  List<Integer> idList = new ArrayList<>();
  idList.add(4);
  idList.add(7);
  userMapper.deleteBatchIds(idList);
 }
 /**SQL statement:
 DELETE FROM student WHERE id In (4,7)
 **/

4)select

Query operation in our development is the most often used, but also the most important.MybatisPlusThere are also many ways to support query in, as follows:

 T selectById(Serializable id);
 ​
 List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
 ​
 List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
 ​
 T selectOne(@Param("ew") Wrapper<T> queryWrapper);
 ​
 Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
 ​
 List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
 ​
 List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
 ​
 List<Object> selectObjs(@aram("ew") Wrapper<T> queryWrapper);
 ​
 IPage<T> selectPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper);
 ​
 IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper);

You can see that there are a total of10Next, we will test one by one

Query all
@Test
 public void selectList() {
  List<User> users = userMapper.selectList(null);
  users.forEach(System.out::println);
 }
 /** 
  OUTPUT:
 User (id = 1, deptid = 1, name = side dish, remark = pay attention to side dish, don't get lost! )
 User (id = 2, deptid = 1, name = Xiao Ming, remark = study hard, make progress every day!)
  SQL statement:
 SELECT id, dept_id, name, remark FROM student;
 **/
Number of queries
@Test
 public void selectCount() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  queryWrapper.like ("name", "small");
  System.out.println(userMapper.selectCount(queryWrapper));
 }
 /** 
  OUTPUT:
 2
  SQL statement:
 Select count (1) from student where (name like '% small%');
 **/
Query by ID
@Test
 public void selectById() {
  User user = userMapper.selectById(1);
  System.out.println(user);
 }
 /** 
  OUTPUT:
 User (id = 1, deptid = 1, name = side dish, remark = pay attention to side dish, don't get lost! )
  SQL statement:
 SELECT id, dept_id, name, remark FROM student WHERE ID = 1;
 **/
Batch query by ID
@Test
 public void selectBatchIds() {
  List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2));
  users.forEach(System.out::println);
 }
 /** 
  OUTPUT:
 User (id = 1, deptid = 1, name = side dish, remark = pay attention to side dish, don't get lost! )
 User (id = 2, deptid = 1, name = Xiaoming, remark = study hard and make progress every day! )
  SQL statement:
 SELECT id, dept_id, name, remark FROM student WHERE ID IN (1, 2);
 **/
Query single item according to condition
@Test
 public void selectOne() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  queryWrapper.eq ("name", "side dish");
  User user = userMapper.selectOne(queryWrapper);
  System.out.println(user);
 }
 /**
  OUTPUT:
 User (id = 1, deptid = 1, name = side dish, remark = pay attention to side dish, don't get lost! )
  SQL statement:
  SELECT id, name, dept_ ID, remark from student where (name ='side dish ');
 **/
Query multiple items according to conditions

adoptmapPass parameters, not throughLIKEQuery, but through=query

@Test
 public void selectByMap() {
  HashMap<String, Object> columnMap = new HashMap<>();
  columnMap.put ("name", "small");
  List<User> users = userMapper.selectByMap(columnMap);
  users.forEach(System.out::println);
 }
 /**
  OUTPUT:
 null
  SQL statement:
 SELECT id, name, dept_ ID, remark from student where name ='small ';
 **/

If we don’t create a new entity class to encapsulate the result, we can also use theMapTo receive the result set:

@Test
 public void selectMaps() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  queryWrapper.like ("name", "small");
  List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
  maps.forEach(System.out::println);
 }
 /**
  OUTPUT:
 {name = pickle, remark = follow pickle, don't get lost, id = 1, Dept? Id = 1}
 {name = Xiao Ming, remark = study hard, make progress every day, id = 2, Dept? Id = 1}
  SQL statement:
 SELECT id, name, dept_id, remark FROM student WHERE (name LIKE '% Small% ';
 **/

It can also be usedObjectObject to receive the result set:

@Test
 public void selectObjs() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  queryWrapper.like ("name", "small");
  List<Object> objects = userMapper.selectObjs(queryWrapper);
 }
 /**
  OUTPUT:
 {name = small dish, remark = pay attention to small dish, don't get lost! , id=1, dept_ id=1}
 {name = Xiao Ming, remark = study hard and make progress every day! , id=2, dept_ id=1}
  SQL statement:
 SELECT id, name, dept_ ID, remark from student where (name like '% small%');
 **/
Paging query
@Test
 public void selectPage() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  queryWrapper.like ("name", "small");
  Page<User> page = new Page<>(1, 1);
  IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
  System.out.println (total data:+ userIPage.getTotal ());
  System.out.println (total pages:+ userIPage.getPages ());
  System.out.println (current page:+ userIPage.getCurrent ());
  System.out.println (page size:+ userIPage.getSize ());
  userIPage.getRecords().forEach(System.out::println);
 }
 /**
  OUTPUT:
 Total data: 2
 Total pages: 2
 Current page: 1
 Page size: 1
 User (id = 1, deptid = 1, name = side dish, remark = follow side dish, don't get lost!)
  SQL statement:
  SELECT id, name, dept_id, remark
  FROM student
  Where (name like '% small%')
  LIMIT 0,1;
 **/

3. Conditional constructor

Improve productivity, the most complete mybatis plus explanation!

stayCRUDIn the basic operation of, we want to query by the conditionWrapperClass, the above is simply usedeqandlikeOperation. In fact, this class is very powerful, which we will describe in detail below.

1)allEq

wholeeqOr individuallyisNull

 allEq(Map<R, V> params)
 allEq(Map<R, V> params, boolean null2IsNull)
 allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
  
 allEq(BiPredicate<R, V> filter, Map<R, V> params)
 allEq(BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull)
 allEq(boolean condition, BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull) 

Parameter Description:

param:Key is the database field name and value is the field value

nullsIsNull:If true, it is called when the value of the map is nullisNullMethod, if it is false, it will be ignored and will not be called when value is nullisNullmethod

filter:Filter function to determine whether the field is allowed to be passed into the comparison condition

Use example:

  • allEq(Map<R, V> params)
@Test
 public void testAllEq() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  Map<String,Object> params = new HashMap<>();
  params.put ("name", "side dish");
  params.put("dept_id",1);
  params.put("remark",null);
  queryWrapper.allEq (params); // the isnull method is called
  userMapper.selectList(queryWrapper);
 }
 /** 
  result:
 {}
  SQL statement:
  SELECT id,name,dept_id,remark
  FROM student
  Where (name ='side dish 'and Dept_ id = 1 AND remark IS NULL);
  **/
  • allEq(Map<R, V> params, boolean null2IsNull)
@Test
 public void testAllEq() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  Map<String,Object> params = new HashMap<>();
  params.put ("name", "side dish");
  params.put("dept_id",1);
  params.put("remark",null);
  queryWrapper.allEq (params, false); // isnull method will not be called
  userMapper.selectList(queryWrapper);
 }
 /** 
  result:
 User (id = 1, deptid = 1, name = side dish, remark = pay attention to side dish, don't get lost! )
  SQL statement:
  SELECT id,name,dept_id,remark
  FROM student
  Where (name ='side dish 'and Dept? Id = 1);
  **/
  • allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
@Test
 public void testAllEq() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  Map<String,Object> params = new HashMap<>();
  params.put ("name", "side dish");
  params.put("dept_id",1);
  params.put("remark",null);
  queryWrapper.allEq (false, params, false); // no condition will be brought in for query
  userMapper.selectList(queryWrapper);
 }
 /** 
  result:
 {name = small dish, remark = pay attention to small dish, don't get lost! , id=1, dept_ id=1}
 {name = Xiao Ming, remark = study hard and make progress every day! , id=2, dept_ id=1}
  SQL statement:
  SELECT id,name,dept_id,remark
  FROM student;
  **/
  • allEq(BiPredicate<R, V> filter, Map<R, V> params)
@Test
 public void testAllEq() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  Map<String, Object> params = new HashMap<>();
  params.put ("name", "side dish");
  params.put("dept_id", 1);
  params.put("remark", null);
  //Only "m" in key can be used as condition judgment
  queryWrapper.allEq((k, v) -> (k.contains("m")), params);
  userMapper.selectList(queryWrapper);
 }
 /** 
  result:
 0
  SQL statement:
  SELECT id,name,dept_id,remark
  FROM student
  Where (name ='side dish 'and remark is null);
  **/

2) Comparison operation

  • eq:amount to=
  • ne:amount to!=
  • gt:amount to>
  • ge:amount to>=
  • lt:amount to<
  • le:amount to<=
  • between:amount tobetween ... and ...
  • notBetween:amount tonot between ... and ...
  • in:amount toin(.., .., ..)
  • notIn:amount tonot in(.., .., ..)

3) Fuzzy query

  • like: Like ("name", "side dish") > "name like"% side dish% "
  • notLike: Notlike ("name", "side dish") > > name not like "% side dish%"
  • likeLeft: Like ("name", "side dish") > "name like"% "side dish"
  • likeRight: Like ("name", "side dish") > "name like" side dish% "

4) Sort

  • orderBy:
 orderBy(boolean condition, boolean isAsc, R... columns)

orderBy(true, true, "id", "name") --> order by id ASC, name ASC

  • orderByAsc:
`orderByAsc("id","name") --> order by id ASC, name ASC`
  • orderByDesc:
orderByDesc("id","name) --> order by id Desc, name Desc`

5) Logical query

  • or:

Splicing: active callorIt means that the next method is not usedandConnect! (do not callorThe default is useandConnection),EQ ("Id", 1). Or (). EQ ("name", "Lao Wang")

Nesting:Or (I - > i.eq ("name", "Li Bai"). Ne ("status", "alive"))

  • and:

Nesting:And (I - > i.eq ("name", "Li Bai"). Ne ("status", "alive"))

6)select

In MP query, all fields are queried by default. If necessary, you can specify the fields through the select method, such asselect("id", "name")

4. Configuration explanation

1) Basic configuration

  • configLocation

Used to indicateMyBatisThe location of the configuration file, if we have oneMyBatisYou need to configure the path of the configuration file toconfigLocationin

SpringBoot:

 mybatis-plus.config-location = classpath:mybatis-config.xml

SpringMvc:

 <bean id="sqlSessionFactory"
 class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
 <property name="configLocation" value="classpath:mybatis-config.xml"/>
 </bean
  • mapperLocations

Used to indicateMapperCorrespondingXMLThe location of the file, we are inUniversal CRUDUsed inMapperIt’s direct successionMPProvidedBaseMapper, we can also customize the method, and thenXMLCustom in fileSQLAnd then we need to tell themMapperCorrespondingXMLLocation of the file

SpringBoot:

 mybatis-plus.mapper-locations = classpath*:mybatis/*.xml

SpringMVC:

 <bean id="sqlSessionFactory"
 class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
 <property name="mapperLocations" value="classpath*:mybatis/*.xml"/>
 </bean>
  • typeAliasesPackage

be used forMyBatisScan path of alias package. Through this property, you can register aliases for classes in the package. After registration, you canMapperCorrespondingXMLThe class name can be used directly in the file instead of the fully qualified class name

SpringBoot:

 mybatis-plus.type-aliases-package = cbuc.life.bean

SpringMVC:

 <bean id="sqlSessionFactory"
 class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
 <property name="typeAliasesPackage"
 value="com.baomidou.mybatisplus.samples.quickstart.entity"/>
 </bean>

2) Advanced configuration

  • mapUnderScoreToCamelCase

Whether to enable automatic hump naming rule mapping. The default value of this configuration istrue, but this propertyMyBatisThe default value in isfalseSo in our normal development, we will turn on this configuration.

# turn off automatic hump mapping. This parameter cannot be used with mybatis- plus.config -Location exists at the same time
 mybatis-plus.configuration.map-underscore-to-camel-case = false

  • cacheEnabled

Globally turn on or off any cache configured by all mappers in the configuration file. The default istrue

 mybatis-plus.configuration.cache-enabled = false

3) DB policy configuration

  • idType

The global default primary key type. After setting, you can omit the primary key in the entity object@TableId(type = IdType.AUTO)to configure. The default value for this configuration isID_WORKER

SpringBoot:

 mybatis-plus.global-config.db-config.id-type = auto

SpringMVC:

 <bean id="sqlSessionFactory"
 class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource"/>
      <property name="globalConfig">
          <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
              <property name="dbConfig">
                  <bean         class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
                  <property name="idType" value="AUTO"/>
                  </bean>
              </property>
          </bean>
      </property>
 </bean>
  • tablePrefix

Prefix of table name, which can be omitted after global configuration@TableName()to configure. The default value for this configuration isnull

SpringBoot:

 mybatis-plus.global-config.db-config.table-prefix = yq_

SpringMVC:

 <bean id="sqlSessionFactory"
 class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource"/>
      <property name="globalConfig">
          <bean class="com.baomidou.mybatisplus.core.config.GlobalConfig">
              <property name="dbConfig">
                  <bean            class="com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig">
                      <property name="idType" value="AUTO"/>
                      <property name="tablePrefix" value="yq_"/>
                  </bean>
              </property>
          </bean>
      </property>
 </bean>

5. Other extensions

1) Auto fill

Sometimes when we insert or update data, we want some fields to be filled automatically. For example, we usually have one in the data sheetInsert timeperhapsUpdate timeFor this kind of field, we will fill in the current time by defaultMPWe can also configure it in.

First of all, we need help@TableField(fill = FieldFill.INSERT)This annotation is filled when it is inserted.

 @TableField(fill = FieldFill.INSERT)
 private String remark;

The automatic filling mode is as follows:

public enum FieldFill {
  /**
  *Do not handle by default
  */
  DEFAULT,
  /**
  *Fill in fields on insert
  */
  INSERT,
  /**
  *Fill in fields on update
  */
  UPDATE,
  /**
  *Fill in fields on insert and update
  */
  INSERT_UPDATE
 }

Then we write a custom fill processing mode

@Component
 public class MyMetaObjectHandler implements MetaObjectHandler {
  @Override
  public void insertFill(MetaObject metaObject) {
  Object remark = getFieldValByName("remark", metaObject);
  if (null == remark) {
  Setfieldvalbyname ("remark", "study hard", metaobject);
  }
  }
 ​
  @Override
  public void updateFill(MetaObject metaObject) {
  //Custom fill on update
  }
 }

Test:

@Test
 public void testObjectHandler() {
  User user =  User.builder (). Deptid (1). Name ("Xiao Ming"). Build();
  userMapper.insert(user);
 }
 /**
  SQL statement:
 INSERT INTO student ( name, dept_id, remark )
 Values ('xiao Ming ', 1,' study hard ');
 **/

You can see that the fields we filled in have been automatically merged when inserting.

2) Logical deletion

In the development, many times we do not need to delete data in the real sense of physical deletion, but use logical deletion. In this way, we need state conditions to ensure that the marked data will not be queried.MPOf course, this function is also supported.

We need to do it firststudentTable to add a fieldstatusTo declare whether the data is deleted,0 means deleted, 1 means not deletedThen you need to add this attribute to the entity class:

 @TableLogic
 private Integer status;

stayapplication.yamlMedium configuration:

 mybatis-plus:
  global-config:
  db-config:
  logic-delete-value: 0
  logic-not-delete-value: 1

Test:

@Test
 public void testLogicDelete() {
  userMapper.deleteById(1);
 }
 /**
  SQL statement:
 UPDATE student SET status=0
 WHERE id=1 AND status=1;
 **/

We can see that this paragraphSQLThere is no real deletion, but a logical deletion, just an update of the deletion ID

3) General enumeration

If there are fields like gender, we usually use0and1But we have to do value conversion. At this time, we can use enumeration to solve this problem

First of allstudentTable to add asexField to represent gender,0 for female, 1 for male, and then define an enumeration class:

public enum SexEnum implements IEnum<Integer> {
  Man (1, "male"),
  Women (0, "female");
 ​
  private int code;
 ​
  private String value;
 ​
  SexEnum(int code, String value) {
  this.code = code;
  this.value = value;
  }
 ​
  @Override
  public Integer getValue() {
  return this.code;
  }
  
  //Be careful to override this method, otherwise the value will be converted to 'man' instead of 'man'
  @Override
  public String toString() {
  return this.value;
  }
 }

Then add the corresponding attribute in the entity class

 private SexEnum sex;

stayapplication.yamlMedium configuration:

 mybatis-plus:
  type-enums-package: cbuc.life.enums

Test:

@Test
 public void selectOne() {
  QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  queryWrapper.eq ("name", "side dish");
  User user = userMapper.selectOne(queryWrapper);
  System.out.println(user);
 }
 /**
  Output results:
 User (id = 1, deptid = 1, name = side dish, remark = pay attention to side dish, don't get lost! , status = 1, sex = male)
  SQL statement:
  SELECT id,sex,name,dept_id,remark,status
  FROM student
  Where status = 1 and (name ='side dish ');
 **/

END

This article ends here. The content is a bit long, but if you can read it completely, I’m sure you can use it very wellMybatisPlusla It’s a long way to go. I’ll search with you!

Improve productivity, the most complete mybatis plus explanation!

Today’s you work harder, tomorrow’s you will be able to say less words to ask for help!

I am Xiaocai, a man who studies with you. 💋

The official account of WeChat has been opened.A good story of a small dishIf you don’t pay attention, remember to pay attention!