Mybatis-Plus快速入门

Mybatis-Plus快速入门

一、基础环境配置

  1. 添加依赖(Maven)

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.3.1</version>
    </dependency>
    
  2. 配置数据源application.yml

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

二、核心概念与组件

1. 实体类注解
import com.baomidou.mybatisplus.annotation.*;

@TableName("user")  // 对应数据库表名
public class User {
    @TableId(type = IdType.AUTO)  // 主键策略:自增
    private Long id;
    
    private String username;
    
    @TableField(fill = FieldFill.INSERT)  // 自动填充
    private Date createTime;
    
    @TableLogic  // 逻辑删除
    private Integer deleted;
}
2. Mapper 接口
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface UserMapper extends BaseMapper<User> {
    // 继承 BaseMapper 后自动拥有 CRUD 方法
}

三、必学查询方法

1. 单表查询
// 1. 根据 ID 查询
User user = userMapper.selectById(1L);

// 2. 查询列表(带条件)
List<User> list = userMapper.selectList(
    new LambdaQueryWrapper<User>()
        .eq(User::getUsername, "test")  // WHERE username = 'test'
        .gt(User::getAge, 18)           // AND age > 18
        .orderByDesc(User::getCreateTime)  // ORDER BY create_time DESC
);

// 3. 分页查询
IPage<User> page = new Page<>(1, 10);  // 第1页,每页10条
IPage<User> result = userMapper.selectPage(
    page,
    new LambdaQueryWrapper<User>().eq(User::getStatus, 1)
);
2. 条件构造器
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper
    .eq(User::getUsername, "test")     // =
    .ne(User::getAge, 18)              // !=
    .like(User::getNickname, "张")     // LIKE '%张%'
    .between(User::getAge, 20, 30)     // BETWEEN 20 AND 30
    .in(User::getId, Arrays.asList(1, 2, 3))  // IN (1,2,3)
    .orderByDesc(User::getCreateTime); // ORDER BY create_time DESC

四、增删改操作

// 1. 插入
User user = new User();
user.setUsername("test");
user.setAge(20);
int rows = userMapper.insert(user);  // 返回影响行数

// 2. 更新(根据 ID)
User user = new User();
user.setId(1L);
user.setAge(21);  // 只更新非 null 字段
int rows = userMapper.updateById(user);

// 3. 条件更新
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper
    .set(User::getAge, 22)  // SET age = 22
    .eq(User::getUsername, "test");  // WHERE username = 'test'
int rows = userMapper.update(null, updateWrapper);

// 4. 删除(逻辑删除)
int rows = userMapper.deleteById(1L);  // 实际执行 UPDATE user SET deleted=1 WHERE id=1

五、分页插件配置

  1. 添加配置类

    import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
    import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class MyBatisPlusConfig {
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
            return interceptor;
        }
    }
    
  2. 使用分页

    IPage<User> page = new Page<>(1, 10);  // 第1页,每页10条
    IPage<User> result = userMapper.selectPage(page, null);
    
    System.out.println("总记录数: " + result.getTotal());
    System.out.println("当前页数据: " + result.getRecords());
    

六、进阶技巧(选学)

1. 动态条件查询
String username = "test";
Integer age = null;

LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper
    .eq(StringUtils.isNotBlank(username), User::getUsername, username)  // 条件动态生效
    .ge(age != null, User::getAge, age);  // 当 age 不为 null 时添加条件

List<User> list = userMapper.selectList(wrapper);
2. 自定义 SQL
// UserMapper.java
public interface UserMapper extends BaseMapper<User> {
    @Select("SELECT * FROM user WHERE age > #{minAge}")
    List<User> selectByAge(@Param("minAge") Integer minAge);
}

七、常见错误处理

  1. 字段映射问题

    • 确保实体类属性名与数据库表字段名一致(或通过 @TableField 注解映射)
    • 开启驼峰命名自动映射:mybatis-plus.configuration.map-underscore-to-camel-case=true
  2. 分页失效

    • 检查是否配置了 PaginationInnerInterceptor 插件
    • 确保 Page 对象作为第一个参数传递给 selectPage 方法
  3. 逻辑删除不生效

    • 检查实体类字段是否添加 @TableLogic 注解

    • 配置逻辑删除全局属性:

      mybatis-plus:
        global-config:
          db-config:
            logic-not-delete-value: 0  # 未删除值
            logic-delete-value: 1      # 已删除值
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值