springboot + mybatis-plus知识总结

1. 介绍

本博客记录学习springboot+mybatis-plus过程中遇到的知识盲点,以及项目开发过程中遇到的细节知识点。

2. BaseMapper 基本方法

2.1 增(insert)

// 定义用户实体类
public class User {
    private Long id;
    private String username;
    private String email;
}
 
// 使用 MyBatis-Plus 提供的 BaseMapper 接口
public interface UserMapper extends BaseMapper<User> {
}
 
// 插入一条记录
User user = new User();
user.setUsername("john_doe");
user.setEmail("john@example.com");
 
// 调用 insert 方法
userMapper.insert(user);

2.2 删(Delete)

// 根据 ID 删除一条记录
userMapper.deleteById(1L);

2.3 改(Update)

// 创建一个用户对象,设置要修改的字段
User user = new User();
user.setId(1L);  // 设置要更新的用户 ID
user.setEmail("newemail@example.com");  // 修改用户邮箱
 
// 更新用户信息
userMapper.updateById(user);

2.4 查(Select)

// 根据 ID 查询用户
User user = userMapper.selectById(1L);
 
// 输出用户信息
System.out.println(user.getUsername());

2.5 条件查询

// 构建查询条件
QueryWrapper<User> queryWrapper = new QueryWrapper<>(); // <-------- 下面会讲到 
 
queryWrapper.eq("username", "john_doe");  // 设置条件:用户名为 john_doe
 
// selectList 方法根据条件查询所有符合条件的记录
List<User> users = userMapper.selectList(queryWrapper);
 
// 输出查询结果
for (User u : users) {
    System.out.println(u.getUsername());
}

3. mybatis-plus 进阶

3.1 自定义sql

可以在Mapper层中使用注解来编写自定义sql,但有sql注入风险。

@Mapper
public interface OutboundMapper extends BaseMapper<Outbound> {
  // #{id}:表示占位符,表示将会被参数 id 的值替换
  @Select("SELECT * FROM table_name WHERE id = #{id}")
  Object selectById(@Param("id") Integer id);
  // 在使用注解时,方法参数可以通过 @Param 注解进行命名,从而在 SQL 中使用
  @Insert("INSERT INTO table_name (column1, column2) VALUES (#{value1}, #{value2})")
  void insert(@Param("value1") String value1, @Param("value2") Integer value2);

  @Update("UPDATE table_name SET column1 = #{value1} WHERE id = #{id}")
  void update(@Param("id") Integer id, @Param("value1") String value1);

  @Delete("DELETE FROM table_name WHERE id = #{id}")
  void delete(@Param("id") Integer id);
}

3.2 返回值处理

sql 查询的返回值可以是单个对象、多个对象的列表或简单的原始类型(如 intString等)。

  • 单个对象
@Select("SELECT * FROM users WHERE id = #{id}")
User selectById(@Param("id") Integer id);
  • 列表
@Select("SELECT * FROM users")
List<User> selectAll();
  • 原始类型
@Select("SELECT COUNT(*) FROM users")
int countUsers();

3.3 事务处理

可以使用Spring的@Transactional注解来管理事务。

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
 
    @Transactional
    public void createUser(User user) {
        userMapper.insert(user);
        // 其他逻辑...
    }
}

4. 注解

4.1 @RequiredArgsConstructor

Lombok 库提供的一个注解,用于在编译时自动生成一个构造函数。它会为类中所有被 final 关键字修饰的未初始化字段,或者带有 @NonNull 注解且未初始化的字段,自动生成一个包含这些参数的构造函数。

@Service
@RequiredArgsConstructor
public class StoreNewServiceImpl extends ServiceImpl<StoreMapper, Store> implements IStoreNewService {
 
    private final StoreRepository storeRepository;
    private final WebClient webClient;
    private final AMapConfig amapConfig;
 
    //业务代码,略
 
}

4.2 @EnableScheduling

  • 定时任务需要在配置类上添加@EnableScheduling,表示对定时任务的支持。
  • 在对应执行任务的方法上添加@Scheduled,声明需要执行定时任务的方法。
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
@EnableScheduling
public class Scheduling {
 
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void minute() {
    	System.out.println("==>每天一个小时执行一次");
    }
    
    @Scheduled(fixedRate=2000)
    public void count() {
    	System.out.println("==>上一次开始执行时间点后2秒再次执行");
    }
 
    @Scheduled(fixedDelay=2000)
    public void fixedDelay(){
    	System.out.println("==>上一次执行完毕时间点后2秒再次执行");
    }
    
    // 初始时延迟3秒,每隔10秒
    @Scheduled(initialDelay=1000, fixedDelay=2000)
    public void fixedRate(){
    	System.out.println("==>第一次延迟1秒执行,然后在上一次执行完毕时间点后2秒再次执行");
    }
}

4.3 @Slf4j

Lombok将自动生成一个名为 log 的日志记录器字段。

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyClass {
    public void doSomething() {
        log.debug("Debug message");
        log.info("Info message");
        log.warn("Warning message");
        log.error("Error message");
    }
}

5. 参考

mybatis plus 常用知识汇总(保姆级教程!~)
mybatis-plus官方接口文档

posted @ 2025-08-25 17:03  esico  阅读(16)  评论(0)    收藏  举报