Mybatis-Plus详解01-代码生成器&增删改查基本使用

作者:da吃一鲸8862024.01.17 09:12浏览量:7

简介:本文介绍了Mybatis-Plus的代码生成器和增删改查的基本使用方法。通过添加依赖、配置代码生成器和运行代码生成器,可以快速生成CRUD代码。增删改查的基本使用则需要创建实体类和Mapper接口,并继承BaseMapper实现CRUD操作。

千帆应用开发平台“智能体Pro”全新上线 限时免费体验

面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用

立即体验

Mybatis-Plus是Mybatis的增强工具,在Mybatis的基础上只做增强不做改变,简化开发、提高效率。
一、代码生成器
Mybatis-Plus的代码生成器功能可以快速生成CRUD代码,极大的提高了开发效率。以下是使用步骤:

  1. 添加依赖
    在pom.xml中添加Mybatis-Plus的依赖,例如:
    1. <dependency>
    2. <groupId>com.baomidou</groupId>
    3. <artifactId>mybatis-plus-boot-starter</artifactId>
    4. <version>3.4.0</version>
    5. </dependency>
  2. 配置代码生成器
    在application.yml中配置代码生成器的相关参数,例如:
    1. mybatis-plus:
    2. global:
    3. db-config:
    4. id-type: auto
    5. logic-delete-value: 1
    6. logic-not-delete-value: 0
    7. logic-delete-field: is_deleted
    8. strategy:
    9. table-prefix: t_
    10. field-strategy:
    11. not-empty: true
    12. not-null: true
    13. table-strategy:
    14. engine: true
    15. comment: true
    16. field-strategy:
    17. not-empty: true
    18. not-null: true
    19. template:
    20. java:
    21. mapper: ${entity.name}Mapper.java
    22. impl: ${entity.name}MapperImpl.java
    23. base: Base${entity.name}Mapper.java
    24. xml:
    25. select: ${entity.name}Mapper.xml
    26. insert: ${entity.name}Mapper.xml
    27. update: ${entity.name}Mapper.xml
    28. delete: ${entity.name}Mapper.xml
  3. 运行代码生成器
    在IDE中运行代码生成器,例如在IntelliJ IDEA中可以使用Run Configuration来运行。在运行前需要先编译项目。
  4. 生成代码目录结构
    代码生成器运行后会生成代码的目录结构,包括生成的实体类、Mapper接口、Mapper XML文件等。
    二、增删改查基本使用
    Mybatis-Plus提供了简单的方法来执行CRUD操作。以下是使用步骤:
  5. 创建实体类和Mapper接口
    根据数据库表结构创建实体类和Mapper接口。例如:
    1. @Data
    2. @TableName("t_") // 表名前缀,使用实体类名前缀的驼峰式命名规则,例如t_user表示表名为user。
    3. public class User {
    4. @TableId(value = "id", type = IdType.AUTO) // 主键字段,使用@TableId注解。类型为自动增长。
    5. private Long id;
    6. @TableField("user_name") // 字段名,使用@TableField注解。与数据库字段名对应。
    7. private String userName;
    8. @TableField("password") // 字段名,使用@TableField注解。与数据库字段名对应。
    9. private String password;
    10. }
    ```java
    public interface UserMapper extends BaseMapper {} // 继承BaseMapper,实现CRUD操作。
article bottom image

相关文章推荐

发表评论