Mybatis-Plus详解01-代码生成器&增删改查基本使用
2024.01.17 09:12浏览量:7简介:本文介绍了Mybatis-Plus的代码生成器和增删改查的基本使用方法。通过添加依赖、配置代码生成器和运行代码生成器,可以快速生成CRUD代码。增删改查的基本使用则需要创建实体类和Mapper接口,并继承BaseMapper实现CRUD操作。
千帆应用开发平台“智能体Pro”全新上线 限时免费体验
面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用
立即体验
Mybatis-Plus是Mybatis的增强工具,在Mybatis的基础上只做增强不做改变,简化开发、提高效率。
一、代码生成器
Mybatis-Plus的代码生成器功能可以快速生成CRUD代码,极大的提高了开发效率。以下是使用步骤:
- 添加依赖
在pom.xml中添加Mybatis-Plus的依赖,例如:<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
- 配置代码生成器
在application.yml中配置代码生成器的相关参数,例如:mybatis-plus:
global:
db-config:
id-type: auto
logic-delete-value: 1
logic-not-delete-value: 0
logic-delete-field: is_deleted
strategy:
table-prefix: t_
field-strategy:
not-empty: true
not-null: true
table-strategy:
engine: true
comment: true
field-strategy:
not-empty: true
not-null: true
template:
java:
mapper: ${entity.name}Mapper.java
impl: ${entity.name}MapperImpl.java
base: Base${entity.name}Mapper.java
xml:
select: ${entity.name}Mapper.xml
insert: ${entity.name}Mapper.xml
update: ${entity.name}Mapper.xml
delete: ${entity.name}Mapper.xml
- 运行代码生成器
在IDE中运行代码生成器,例如在IntelliJ IDEA中可以使用Run Configuration来运行。在运行前需要先编译项目。 - 生成代码目录结构
代码生成器运行后会生成代码的目录结构,包括生成的实体类、Mapper接口、Mapper XML文件等。
二、增删改查基本使用
Mybatis-Plus提供了简单的方法来执行CRUD操作。以下是使用步骤: - 创建实体类和Mapper接口
根据数据库表结构创建实体类和Mapper接口。例如:
```java@Data
@TableName("t_") // 表名前缀,使用实体类名前缀的驼峰式命名规则,例如t_user表示表名为user。
public class User {
@TableId(value = "id", type = IdType.AUTO) // 主键字段,使用@TableId注解。类型为自动增长。
private Long id;
@TableField("user_name") // 字段名,使用@TableField注解。与数据库字段名对应。
private String userName;
@TableField("password") // 字段名,使用@TableField注解。与数据库字段名对应。
private String password;
}
public interface UserMapper extends BaseMapper{} // 继承BaseMapper ,实现CRUD操作。

发表评论
登录后可评论,请前往 登录 或 注册