MyBatis-Plus 常用注解

相关标签:1.MyBatis 更流畅的使用体验
2.强大实用:MyBatis 与三种流式查询方法

MyBatis-Plus 常用注解

那些年,我们一起学过的 MyBatis-Plus 常用注解

一、MyBatis-Plus 常用注解简介

最近学习了 MyBatis-Plus,现在带大家回顾一下在学习过程中经常用到哪些注解,这些注解有什么功能?如何使用这些注解?特别适合新手学习和老手复习~

话不多说,让我们开始吧!

2. MyBatis-Plus 简介
MyBatis-Plus(简称 MP)是 MyBatis 的增强工具。在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

愿景是做 MyBatis 最好的搭档!

官方地址:https://baomidou.com/

文档发布地址:https://baomidou.com/pages/24112f



3.MyBatis-Plus 常用注解·常用注解
1. @MapperScan
@SpringBootApplication _
@MapperScan ( " com.cabbage.mapper " )
public class Mybatisplus01Application {
public static void main( String[] args ) {
SpringApplication.run ( Mybatisplus01Application.class, args );
}
}

结合代码和图片,大家可以猜到:@MapperScan 注解用于扫描 mapper 映射文件,只有使用了它才能使用官方提供的各种方法。

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);
}

为什么再次介绍这个注解呢?因为 @Mapper 作用于数据库中的实体类,不需要再写 @MapperScan 注解。它们的区别在于:@Mapper 只能映射一个实体类,而 @MapperScan 可以映射整个包下的实体类,范围更广,操作更方便。

3. @TableName
先看以下代码:

@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 ;
}



大家都知道,当实体类的类名与要操作的表名不一致时会报错,@TableName 注解可以帮助我们解决这个问题。数据库表名是 t_user,实体类名是 User,只需在类名上写 @TableName("t_user") 即可。

4. @Data
这个注解也大幅简化了开发。为什么这么说呢?因为使用这个注解后,可以省略 getter()、setter()、toString(),以及类的 equals() 和 hashCode() 方法的重写。是不是很惊喜?

5. @TableId
MyBatis-Plus 执行增删改查时,默认使用 id 作为主键列,插入数据时默认
基于雪花算法生成 id,这里不展开讲解雪花算法。

使用 @TableId(value = "id") 时,如果实体类和表中的主键不是 id 而是其他字段(如代码中的 uid),MyBatis-Plus 会自动识别 uid 为主键列,否则会报错:

使用 @TableId(value = "id", type = IdType.AUTO) 表示使用数据库自增策略。注意,使用此 type 时请确保数据库已设置 id 自增,否则会失效!

当然,@TableId 的功能也可以写在 application.yml 配置文件中,配置如下:

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 执行 SQL 语句时,必须保证实体类中的属性名与表中的字段名相同,否则会报错。@TableField(value = "is_deleted") 表示将数据库表中的 is_deleted 与实体类中的 isDeleted 字段名对应。

注意:

如果实体类属性使用驼峰命名风格,表中字段使用下划线命名风格
例如实体类属性 userName,表字段 user_name,MyBatis-Plus 会自动将下划线命名风格转换为驼峰命名风格
如果实体类属性与表中字段不符合上述条件,如实体类属性 name 与表字段 username,需要在实体类属性上使用 @TableField("username") 设置该属性对应的字段名

7. @TableLogic

在讲这个注解之前,先来了解一下逻辑删除。

物理删除:真实删除,从数据库中删除对应数据,删除后无法查询到该数据
逻辑删除:假删除,将对应数据中表示是否删除的字段状态改为"已删除状态",数据库中仍可查看该数据记录
使用场景:可数据恢复

在我的数据库表中,is_delete 为1时表示逻辑删除,is_delete 为0时表示未删除
@TableLogic 注解表示类中的属性为逻辑删除属性

注意:

测试逻辑删除时,实际执行的是 UPDATE t_user SET is_deleted =1 WHERE id=? AND is_deleted =0
测试查询功能时,已逻辑删除的数据默认不会被查询 SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted =0
学习 MyBatis-Plus 分页插件时,需要配置拦截器,参见代码:

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

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

8. @Configuration
相信大家已经多次看到这个注解了,可能有点不耐烦,但我还是要在这里提一下。使用此注解的类代表配置类,该类本身也是一个 Bean。还可以在此类中使用 @Bean 注解加载 Bean

9. @Bean
@Bean 注解表示将方法中的对象注入到 Spring 容器中,方便后续从容器中取出对象以简化开发。通常与 @Configuration 注解配合使用。相信大家经常看到这个注解,这里就不多说了~

讲完了分页插件,来看看基本用法。


@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 ());
}

运行结果:


10. @Param
使用自定义分页语句时:

@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 由 MyBatis 提供。作为 Dao 层注解,用于传递参数,使其与 SQL 中的字段名对应,简化开发~

11. @Version
学习乐观锁时,一定见过以下代码:

@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;
}
}

@Version 是实现乐观锁的重要注解。当数据库中的数据需要更新时(如 price),version 会递增1。如果 where 语句中的 version 不正确,更新将失败。

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

@EnumValue 注解标识的属性值将存储到数据库中,相当于 INSERT INTO t_user (username, age, sex) VALUES (?, ?, ?)
参数:Enum(String)、20(Integer)、1(Integer)

4.MyBatis 常用注解·总结


好了,MyBatis-Plus 的常用注解差不多讲完了。相信大家已经感受到了国产框架的便捷支持,希望大家积极支持。如果觉得博主写得不错,可以给博主三连支持~~

相关文章

探索更多特惠

  1. 短信服务(SMS)与邮件服务

    5万封邮件包低至1.99 USD,120条短信仅需1.00 USD

phone 联系我们
你好,我是AI助理。
可以解答问题、推荐解决方案等。