SpringBoot整合MyBatis-Plus全攻略:从零实现高效CRUD

一、MyBatis-Plus核心优势

MyBatis-Plus作为MyBatis的增强工具包,在保留原生特性的基础上,提供了多项开箱即用的功能:

  1. 自动生成基础CRUD操作
  2. 内置代码生成器(3.5.3+版本支持最新模板引擎)
  3. 强大的条件构造器Wrapper
  4. 支持Lambda形式调用
  5. 主键自动生成策略(支持雪花算法、UUID等)

二、环境搭建与配置

1. 创建SpringBoot项目

使用Spring Initializr创建项目时选择以下依赖:

  • Spring Web
  • MyBatis-Plus(3.5.3.1)
  • MySQL Driver
  • Lombok

2. 数据库配置

# application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mp_demo?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

# MyBatis-Plus配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.global-config.db-config.id-type=assign_id

3. 分页插件配置

@Configuration
public class MybatisPlusConfig {
    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

三、基础结构搭建

1. 实体类定义

@Data
@TableName("t_user")
public class User {
    @TableId(type = IdType.ASSIGN_ID)
    private Long id;
    private String username;
    private Integer age;
    private String email;
    @TableField("create_time")
    private LocalDateTime createTime;
}

2. Mapper接口开发

public interface UserMapper extends BaseMapper<User> {
}

3. 服务层实现

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

public interface UserService extends IService<User> {
}

四、完整CRUD实现案例

1. 新增操作

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 单个新增
    @PostMapping
    public Result addUser(@RequestBody User user) {
        return Result.success(userService.save(user));
    }

    // 批量新增
    @PostMapping("/batch")
    public Result batchAdd(@RequestBody List<User> users) {
        return Result.success(userService.saveBatch(users));
    }
}

2. 删除操作

// 根据ID删除
@DeleteMapping("/{id}")
public Result deleteById(@PathVariable Long id) {
    return Result.success(userService.removeById(id));
}

// 条件删除
@DeleteMapping
public Result deleteByCondition(@RequestBody Map<String, Object> params) {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    params.forEach((key, value) -> wrapper.eq(key, value));
    return Result.success(userService.remove(wrapper));
}

3. 修改操作

// 全量更新
@PutMapping
public Result updateUser(@RequestBody User user) {
    return Result.success(userService.updateById(user));
}

// 条件更新
@PatchMapping("/{id}")
public Result partialUpdate(@PathVariable Long id, 
                           @RequestBody Map<String, Object> updates) {
    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.eq("id", id);
    updates.forEach((key, value) -> wrapper.set(key, value));
    return Result.success(userService.update(wrapper));
}

4. 查询操作

基础查询
// ID查询
@GetMapping("/{id}")
public Result getById(@PathVariable Long id) {
    return Result.success(userService.getById(id));
}

// 全量列表
@GetMapping
public Result listAll() {
    return Result.success(userService.list());
}
条件查询
// 条件构造器查询
@GetMapping("/search")
public Result searchUsers(@RequestParam String username,
                         @RequestParam Integer minAge) {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.like("username", username)
           .ge("age", minAge)
           .orderByDesc("create_time");
    return Result.success(userService.list(wrapper));
}
分页查询
@GetMapping("/page")
public Result pageQuery(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size) {
    Page<User> pageParam = new Page<>(page, size);
    return Result.success(userService.page(pageParam));
}

五、高级功能实践

1. 自动填充功能

@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;

// 实现MetaObjectHandler
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}

2. 逻辑删除配置

# 开启逻辑删除
mybatis-plus.global-config.db-config.logic-delete-field=deleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

3. 性能分析插件

@Bean
@Profile({"dev", "test"})
public PerformanceInterceptor performanceInterceptor() {
    PerformanceInterceptor interceptor = new PerformanceInterceptor();
    interceptor.setMaxTime(1000);
    interceptor.setFormat(true);
    return interceptor;
}

六、开发建议与最佳实践

  1. 使用LambdaQueryWrapper避免硬编码字段名

    LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
    wrapper.like(User::getUsername, "Tom")
           .ge(User::getAge, 18);
    
  2. 复杂查询建议使用XML映射文件

  3. 批量操作注意事务管理

  4. 定期检查MyBatis-Plus的版本更新

结语

通过本文的整合实践,我们实现了SpringBoot与MyBatis-Plus的无缝对接,覆盖了日常开发中的常见场景。MyBatis-Plus的强大功能可以显著提升开发效率,但其设计哲学是只做增强不做改变,这保证了与原生MyBatis的良好兼容性。建议在实际项目中根据团队规范合理使用各种特性,在提高开发效率的同时保证代码质量。

你可能感兴趣的:(java,spring,boot,mybatis)