MyBatis-Plus 快速入门指南 – wiki基地

MyBatis-Plus 快速入门指南

MyBatis-Plus (MP) 是一个 MyBatis 的增强工具,旨在简化开发,提高效率。它在 MyBatis 的基础上只做增强不做改变,引入它不会对现有项目产生影响。MP 通过提供强大的 CRUD 操作、代码生成器、分页插件等功能,让开发者可以专注于业务逻辑的实现,而无需编写大量的重复代码。

本文将详细介绍 MyBatis-Plus 的快速入门指南,涵盖从环境搭建到高级特性的使用,帮助你快速掌握 MP 并应用到实际项目中。

一、环境搭建

  1. 引入依赖:

在你的 pom.xml 文件中添加 MyBatis-Plus 的依赖:

“`xml

com.baomidou
mybatis-plus-boot-starter
3.5.3.1


mysql
mysql-connector-java
runtime

“`

  1. 配置数据源:

application.propertiesapplication.yml 文件中配置数据库连接信息:

yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
username: your_username
password: your_password
driver-class-name: com.mysql.cj.jdbc.Driver

  1. 配置 MyBatis-Plus:

yaml
mybatis-plus:
mapper-locations: classpath*:/mapper/*.xml # Mapper XML 文件的位置
type-aliases-package: com.example.demo.entity # 实体类所在的包
global-config:
db-config:
id-type: auto # 主键生成策略,auto 表示数据库自增
logic-delete-value: 1 # 逻辑删除值
logic-not-delete-value: 0 # 未逻辑删除值
table-prefix: t_ # 表名前缀

二、创建实体类和 Mapper 接口

  1. 实体类:

创建一个实体类,并使用 @TableName 注解指定对应的数据库表名,使用 @TableId 注解指定主键字段。

“`java
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

@Data
@TableName(“t_user”)
public class User {

   @TableId(type = IdType.AUTO)
   private Long id;

   private String name;

   private Integer age;

   @TableLogic
   private Integer deleted; // 逻辑删除字段

}
“`

  1. Mapper 接口:

创建一个继承 BaseMapper 的 Mapper 接口,无需编写任何方法即可拥有丰富的 CRUD 功能。

“`java
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper {
}
“`

三、进行 CRUD 操作

在 Service 层注入 UserMapper,即可使用 MP 提供的各种方法进行数据库操作。

“`java
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.stereotype.Service;

@Service
public class UserService extends ServiceImpl {

public User getById(Long id) {
    return this.baseMapper.selectById(id);
}

public boolean save(User user) {
    return this.save(user);
}

public boolean updateById(User user) {
    return this.updateById(user);
}

public boolean removeById(Long id) {
    return this.removeById(id); // 逻辑删除
}

}
“`

四、条件构造器 Wrapper

MP 提供了 QueryWrapperUpdateWrapper 用于构建复杂的查询和更新条件,避免手动拼接 SQL。

“`java
// 查询年龄大于 20 且姓名为 John 的用户
QueryWrapper queryWrapper = new QueryWrapper<>();
queryWrapper.gt(“age”, 20).eq(“name”, “John”);
List users = userMapper.selectList(queryWrapper);

// 将年龄大于 20 的用户的姓名更新为 Jack
UpdateWrapper updateWrapper = new UpdateWrapper<>();
updateWrapper.gt(“age”, 20).set(“name”, “Jack”);
userMapper.update(null, updateWrapper);
“`

五、代码生成器 AutoGenerator

MP 提供了代码生成器,可以快速生成实体类、Mapper 接口、Service 接口和实现类等代码,大大提高开发效率。

java
// 代码生成器配置略,详见官方文档

六、分页插件 PaginationInterceptor

MP 提供了分页插件,方便进行分页查询。

“`java
// 配置分页插件 (在配置类中)
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}

// 使用分页插件
Page page = new Page<>(1, 10); // 当前页码,每页大小
Page userPage = userMapper.selectPage(page, null);
List users = userPage.getRecords(); // 获取当前页数据
long total = userPage.getTotal(); // 获取总记录数
“`

七、乐观锁

MP 支持乐观锁,通过 @Version 注解实现。

“`java
@Data
@TableName(“t_user”)
public class User {
// … other fields

@Version
private Integer version;

}
“`

八、逻辑删除

MP 支持逻辑删除,通过 @TableLogic 注解实现。

“`java
@Data
@TableName(“t_user”)
public class User {
// … other fields

@TableLogic
private Integer deleted;

}
“`

九、性能分析插件 PerformanceInterceptor

MP 提供了性能分析插件,可以监控 SQL 执行时间,帮助优化 SQL 性能.

十、总结

MyBatis-Plus 通过丰富的功能和简洁的 API,大大简化了 MyBatis 的开发流程,提高了开发效率。本文介绍了 MP 的快速入门指南,涵盖了常用功能和特性。希望本文能帮助你快速上手 MP 并应用到实际项目中。 建议结合官方文档进行更深入的学习和探索,以充分发挥 MP 的强大功能。 除了以上内容,MP 还提供了许多其他特性,例如:自动填充、lambda 表达式查询、自定义 SQL 等,可以根据项目需求灵活运用。 通过学习和实践,你将能够更加熟练地使用 MyBatis-Plus,提升开发效率,构建更高效的应用程序。

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部