Mybatis-Plus常见使用

MyBatis-Plus 是 MyBatis 的一个增强工具,它简化了 MyBatis 的开发流程,提供了许多开箱即用的功能,比如通用 Mapper、分页插件、代码生成器等。以下是 MyBatis-Plus 的一些常用方法及其使用场景:


1. 通用 Mapper 方法

MyBatis-Plus 提供了通用 Mapper,无需编写 SQL 即可实现对单表的增删改查操作。

示例代码

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface StaffMapper extends BaseMapper<Staff> {
    // 自定义方法(如果需要)
}

常用方法

  • 插入操作
    int insert(T entity); // 插入一条记录
    
  • 删除操作
    int deleteById(Serializable id); // 根据主键删除
    int deleteByMap(Map<String, Object> columnMap); // 根据条件删除
    int delete(Wrapper<T> queryWrapper); // 根据条件删除
    
  • 更新操作
    int updateById(T entity); // 根据主键更新
    int update(T entity, Wrapper<T> updateWrapper); // 根据条件更新
    
  • 查询操作
    T selectById(Serializable id); // 根据主键查询
    List<T> selectBatchIds(Collection<? extends Serializable> idList); // 根据主键批量查询
    List<T> selectByMap(Map<String, Object> columnMap); // 根据条件查询
    T selectOne(Wrapper<T> queryWrapper); // 查询一条记录
    List<T> selectList(Wrapper<T> queryWrapper); // 查询多条记录
    

2. Wrapper 查询条件

Wrapper 是 MyBatis-Plus 提供的查询条件构造器,支持链式调用,可以方便地构建复杂的查询条件。

常用方法

  • eq: 等于
    QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("username", "admin");
    
  • ne: 不等于
    queryWrapper.ne("status", 0);
    
  • gt: 大于
    queryWrapper.gt("age", 18);
    
  • lt: 小于
    queryWrapper.lt("age", 60);
    
  • like: 模糊查询
    queryWrapper.like("username", "ad");
    
  • in: 包含
    queryWrapper.in("id", Arrays.asList(1, 2, 3));
    
  • orderBy: 排序
    queryWrapper.orderByAsc("create_time");
    

示例

QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("status", 1)
            .like("username", "ad")
            .orderByDesc("create_time");
List<Staff> staffList = staffMapper.selectList(queryWrapper);

3. 分页查询

MyBatis-Plus 提供了分页插件,可以轻松实现分页查询。

配置分页插件

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

分页查询

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

Page<Staff> page = new Page<>(1, 10); // 当前页和每页大小
QueryWrapper<Staff> queryWrapper = new QueryWrapper<>(queryWrapper);
IPage<Staff> staffPage = staffMapper.selectPage(page, queryWrapper);
List<Staff> staffList = staffPage.getRecords(); // 当前页的数据
long total = staffPage.getTotal(); // 总记录数

4. 逻辑删除

MyBatis-Plus 支持逻辑删除,删除操作不会真正删除数据,而是将记录的某个字段标记为删除状态。

配置逻辑删除

在实体类中标记逻辑删除字段:

import com.baomidou.mybatisplus.annotation.TableLogic;

public class Staff {
    @TableLogic
    private Integer deleted;
}

在配置文件中开启逻辑删除:

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: deleted # 逻辑删除字段
      logic-delete-value: 1 # 删除标记值
      logic-not-delete-value: 0 # 未删除标记值

5. 代码生成器

MyBatis-Plus 提供了代码生成器,可以自动生成实体类、Mapper、Service 等代码。

示例配置

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

public class CodeGenerator {
    public static void main(String[] args) {
        AutoGenerator generator = new AutoGenerator();

        // 全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
        globalConfig.setAuthor("YourName");
        globalConfig.setOpen(false);
        generator.setGlobalConfig(globalConfig);

        // 数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/db_name");
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("password");
        generator.setDataSource(dataSourceConfig);

        // 包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.example");
        packageConfig.setMapper("mapper");
        packageConfig.setService("service");
        packageConfig.setController("controller");
        generator.setPackageInfo(packageConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setInclude("staff", "role"); // 需要生成的表
        generator.setStrategy(strategy);

        generator.execute();
    }
}

6. 其他功能

  • 主键生成策略:支持自增、UUID 等主键生成策略。
    @TableId(type = IdType.AUTO)
    private Long id;
    
  • 自动填充:支持自动填充创建时间、更新时间等字段。
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;
    
  • 乐观锁:支持乐观锁机制。
    @Version
    private Integer version;
    

总结

MyBatis-Plus 提供了丰富的功能来简化开发,包括:

  • 通用 Mapper:无需编写 SQL 即可实现单表操作。
  • Wrapper:灵活构建查询条件。
  • 分页查询:轻松实现分页功能。
  • 逻辑删除:支持软删除。
  • 代码生成器:自动生成代码。
  • 其他功能:主键生成、自动填充、乐观锁等。

通过这些功能,开发者可以更高效地完成数据库操作,减少重复代码的编写。

posted @ 2025-03-05 15:07  NONAME-X  阅读(320)  评论(0)    收藏  举报