Common Annotations of Mybatis- Plus

Common annotations of Mybatis- Plus

In those years, the common annotations of Mybatis -Plus that we have learned together

I.Common annotations of Mybatis- Plus Introduction

recently learned mybatis -plus, and now I will take you to review which annotations we often use in the process of learning, and what functions do these annotations have? How to use these annotations? Especially suitable for novice learning and veteran review~

Without further ado , let's get started!

2. Introduction to mybatis -plus
MyBatis -Plus (MP for short) is an enhancement tool for MyBatis . It only enhances and does not change on the basis of MyBatis. It is born to simplify development and improve efficiency .

vision is to be the best partner of MyBatis !

Official address: https://baomidou.com/

Document release address: https://baomidou.com/pages/24112f



3.Common annotations of Mybatis.Commonly used annotations
1. @MapperScan
@SpringBootApplication _
@MapperScan ( " com.cabbage.mapper " )
public class Mybatisplus01Application {
public static void main( String[] args ) {
SpringApplication.run ( Mybatisplus01Application.class, args );
}
}

Combining the code and pictures, the friends can guess: the annotation @ MapperScan is used to scan the mapper mapping file, and only after using it can we use the various methods provided by the official.

2. @Mapper
@Mapper
@Repository
public interface UserMapper extends BaseMapper {
/**
* Query to map collection according to id
* @param id
* @return
*/
Map< String,Object > selectMapById (Long id);
}

Why do I introduce this annotation for the second time? Because @Mapper acts on the entity class in the database, there is no need to write the annotation @MapperScan again . The difference between them is that @Mapper can only map one entity class, while @MapperScan can map the entity class under the entire package. Wider and easier to operate.

3. @TableName
First look at the following code:

@Data
//Set the table name corresponding to the entity class
@TableName("t_user")
public class User {
@TableId(value = "id",type = IdType.AUTO)
private Long uid;
@TableField(value = "name")
private String name;
private Integer age;
private String email;
@TableField(value = "is_deleted")
@TableLogic
private Integer isDeleted ;
}

Everyone knows that when the class name of the entity class type is inconsistent with the table name of the table to be operated, an error will be reported, and the annotation @ TableName can help us solve this problem. My database table name is t_user , and the entity class name is User, just write @TableName (" t_user ") on the class name.

4. @Data
This annotation also greatly simplifies our development. Why do you say this? It's because, using this annotation, you can omit getter(), setter(), toString (), and override the equals() and hashCode () methods of the class. Isn't it surprising to hear this?

5. @TableId
MyBatis -Plus implements addition, deletion , modification and query , it will use id as the primary key column by default, and when inserting data, the default
The strategy based on the snowflake algorithm generates id, and the snowflake algorithm is not explained here.

When using the @TableId (value = "id") statement, if the primary key in the entity class and table is not id, but other fields, such as uid in the code , MyBatis -Plus will automatically identify the uid as the primary key column, otherwise it will Will report this error:

When using the @ TableId (value = " id", type = IdType.AUTO ) statement, it represents the use of the database's auto-increment strategy. Note that for this type , please ensure that the database is set to id auto-increment, otherwise it will be invalid!

Of course, the function of @TableId can also be written in the application.yml configuration file, the configuration is as follows:

mybatis -plus:
global-config:
banner: false
db -config:
# Configure the default prefix of the MyBatis -Plus operation table
table-prefix: "t_"
# Configure the primary key strategy of MyBatis -Plus
id-type: auto
# Configure MyBatis logs
configuration:
log - impl : org.apache.ibatis.logging.stdout.StdOutImpl

6. @TableField
MyBatis -Plus executes the SQL statement, it must ensure that the attribute name in the entity class is the same as the field name in the table, otherwise an error will be reported. The statement @ TableField (value = " is_deleted ") means that the is_deleted in the database table is the same as that in the entity class. The isDeleted field name is the same.

Notice:

If the attributes in the entity class use the camel case naming style, and the fields in the table use the underscore naming style
For example, entity class attribute userName , table field user_name , MyBatis -Plus will automatically convert the underscore naming style to the hump naming style
If the attributes in the entity class and the fields in the table do not meet the above conditions, such as the entity class attribute name and the table field username, you need to use @TableField ("username") on the entity class attribute to set the field name corresponding to the attribute

7. @TableLogic

Before talking about this annotation, let's first understand logical deletion.

Physical deletion: real deletion, delete the corresponding data from the database, and then the deleted data cannot be queried
Logical deletion: Fake deletion, change the status of the corresponding data field representing whether the field has been deleted to "deleted status", and then the data record can still be seen in the database
Usage scenario: data recovery is possible

In my database table, when is_delete is 1, it means logical deletion, and when is_delete is 0, it means no deletion
annotation @TableLogic means that the properties in the class are logically deleted properties

Notice:

When testing tombstones, what is really executed is to modify the UPDATE t_user SET is_deleted =1 WHERE id=? AND is_deleted =0
Test the query function, the tombstoned data will not be queried by default SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted =0
When learning the mybatis -plus paging plugin, we need to configure the interceptor, see the code:

@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor ( ) {
MybatisPlusInterceptor interceptor =
new MybatisPlusInterceptor ( );

interceptor.addInnerInterceptor
(new PaginationInnerInterceptor ( DbType.MYSQL ));
return interceptor;
}
}

8. @Configuration
I believe you have seen this annotation many times, and you may be a little impatient, but I still want to mention it here, the class that uses this annotation represents a configuration class, and the class itself is also a bean. You can also load beans in this class, using the @Bean annotation

9. @Bean
The annotation @Bean indicates that the object in the method is injected into the spring container, and it is convenient to take out the object in the container later to simplify development. It is often used together with the @Configuration annotation. I believe you often see this annotation, so I won't talk about it here~

Now that we have talked about paging plugins, let's take a look at their basic usage.


@Test
void test01() {
//Set paging parameters
Page page = new Page< >( 1, 3);
userMapper.selectPage (page, null);
//Get pagination data
List list = page.getRecords ();
list.forEach ( System.out :: println );
System.out.println ("Current page:" + page.getCurrent ());
System.out.println ("Number of items displayed per page: " + page.getSize ());
System.out.println ("Total records:" + page.getTotal ());
System.out.println ("Total pages: " + page.getPages ());
System.out.println ("Is there a previous page:" + page.hasPrevious ());
System.out.println ("Whether there is a next page: " + page.hasNext ());
}

operation result:


10. @Param
When I use a custom pagination statement:

@Mapper
@Repository
public interface UserMapper extends BaseMapper {
/**
* Query user information by age and paginate
* @param page
* @param age
* @return
*/
Page selectPageByAge ( Page page, @Param("age") Integer age);
}





@Param is provided by MyBatis . As an annotation of the Dao layer, it is used to pass parameters, so that it can correspond to the field name in SQL, which simplifies development~

11. @Version
When we learn optimistic locking, we must have seen the following code:

@Data
@TableName("t_product")
public class Product {
private Long id;
private String name;
private Integer price;
@Version
private Integer version;
}

@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor =
new MybatisPlusInterceptor ( );
//Pagination plugin
interceptor.addInnerInterceptor
(new PaginationInnerInterceptor ( DbType.MYSQL ));
//Optimistic lock plugin
interceptor.addInnerInterceptor (new OptimisticLockerInnerInterceptor ());
return interceptor;
}
}

And this annotation @Version is an important annotation for implementing optimistic locking. When the data in the database is to be updated, such as the price, the version will be incremented by 1. If the version in the where statement is incorrect, the update will fail.

Common annotations of Mybatis.@EnumValue
@Getter
public enum SexEnum {
MALE(1, "男"),
FEMALE(2, "女");
@EnumValue
private Integer sex;
private String sexName;
SexEnum(Integer sex, String sexName) {
this.sex = sex;
this.sexName = sexName;
}
}

mybatis -plus:
global-config:
banner: false
db -config:
# Configure the default prefix of the MyBatis -Plus operation table
table-prefix: "t_"
# Configure the primary key strategy of MyBatis -Plus
id-type: auto
# Configure MyBatis logs
configuration:
log - impl : org.apache.ibatis.logging.stdout.StdOutImpl
# Configure the package corresponding to the type alias
type-aliases-package: cabbage.pojo
# Configure scan general enumeration
type- enums - package: cabbage.pojo

The attribute value identified by the annotation @ EnumValue will be stored in the database, which is equivalent to the statement INSERT INTO t_user ( username, age, sex ) VALUES ( ?, ?, ? )
Parameters: Enum ( String), 20(Integer), 1(Integer)

4.Common annotations of Mybatis. Summary


Well, my friends, the common annotations of mybatis -plus are almost explained. I believe that you have already felt the convenient support of the domestic framework. I hope you will actively support it. If you feel that the blogger's writing is not bad, you can give the blogger three consecutive support ~~

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00