MyBatis-Plus的几种常见用法
创始人
2025-01-07 06:05:06
0

MyBatis-Plus 提供了丰富的高级用法,可以简化开发,提高效率。以下是一些常见的可能会被忽略的用法示例。

1. 乐观锁

乐观锁用于避免在并发环境下数据更新冲突。MyBatis-Plus 通过注解和版本字段实现乐观锁。

示例

  1. 在实体类中添加版本字段,并使用 @Version 注解标记:
import com.baomidou.mybatisplus.annotation.Version;  public class User {     private Long id;     private String name;          @Version     private Integer version;      // Getters and setters } 
  1. 配置乐观锁插件:
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;  @Configuration public class MyBatisPlusConfig {      @Bean     public OptimisticLockerInterceptor optimisticLockerInterceptor() {         return new OptimisticLockerInterceptor();     } } 
  1. 使用乐观锁更新:
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;  @Service public class UserService {      @Autowired     private UserMapper userMapper;      public void updateUser(User user) {         // 更新操作基于版本字段         UpdateWrapper updateWrapper = Wrappers.update()             .eq("id", user.getId())             .eq("version", user.getVersion());                  user.setVersion(user.getVersion() + 1);         userMapper.update(user, updateWrapper);     } } 

2. 异常数据检测和自动填充

MyBatis-Plus 提供了一套通用字段自动填充功能,可以在插入和更新操作时自动填充某些字段。

示例

  1. 创建自动填充处理类:
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component;  @Component public class MyMetaObjectHandler implements MetaObjectHandler {      @Override     public void insertFill(MetaObject metaObject) {         this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);         this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);     }      @Override     public void updateFill(MetaObject metaObject) {         this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);     } } 
  1. 在实体类中使用注解配置自动填充字段:
import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import java.time.LocalDateTime;  public class User {     private Long id;     private String name;      @TableField(fill = FieldFill.INSERT)     private LocalDateTime createTime;          @TableField(fill = FieldFill.INSERT_UPDATE)     private LocalDateTime updateTime;      // Getters and setters } 

3. 逻辑删除

逻辑删除让记录在数据库中实际存在,但对外表现为已删除状态。

示例

  1. 在实体类中添加逻辑删除字段:
import com.baomidou.mybatisplus.annotation.TableLogic;  public class User {     private Long id;     private String name;      @TableLogic     private Integer deleted;      // Getters and setters } 
  1. 配置逻辑删除插件:
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.LogicDeleteInnerInterceptor; 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 LogicDeleteInnerInterceptor());         return interceptor;     } } 

4. 查询链式调用

MyBatis-Plus 提供了丰富的链式查询接口,简化了条件拼接。

示例

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List;  @Service public class UserService {      @Autowired     private UserMapper userMapper;      public List getUsersByName(String name) {         QueryWrapper queryWrapper = new QueryWrapper<>();         queryWrapper.like("name", name)                     .eq("deleted", 0) // 逻辑未删除                     .orderByDesc("createTime");                  return userMapper.selectList(queryWrapper);     } } 

5. 分页查询

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

示例

  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;     } } 
  1. 使用分页查询:
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;  @Service public class UserService {      @Autowired     private UserMapper userMapper;      public IPage getUsersByPage(int page, int size) {         Page userPage = new Page<>(page, size);         return userMapper.selectPage(userPage, null);     } } 

6. 自定义 SQL

MyBatis-Plus 支持在 Mapper 中直接编写自定义 SQL 以满足更复杂的查询需求。

示例

  1. 在 Mapper 接口中定义自定义 SQL:
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select;  public interface UserMapper extends BaseMapper {      @Select("SELECT * FROM user WHERE name = #{name}")     List selectByName(@Param("name") String name);      @Select("SELECT * FROM user WHERE age > #{age}")     IPage selectUsersByAge(Page page, @Param("age") int age); } 
  1. 使用自定义 SQL 查询:
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List;  @Service public class UserService {      @Autowired     private UserMapper userMapper;      public List getUsersByName(String name) {         return userMapper.selectByName(name);     }      public IPage getUsersByAge(int age, int page, int size) {         Page userPage = new Page<>(page, size);         return userMapper.selectUsersByAge(userPage, age);     } } 

以上是 MyBatis-Plus 中几个特别用法的示例,包括乐观锁、自动填充、逻辑删除、链式查询、分页查询和自定义 SQL。通过这些高级用法,你可以大大简化开发、提升代码质量。

相关内容

热门资讯

太实锤了!微信小程序辅助器防检... 您好:这款微信小程序辅助器防检测游戏是可以开挂的,确实是有挂的,很多玩家在这款微信小程序辅助器防检测...
太实锤了透视!水鱼天下脚本,传... 太实锤了透视!水鱼天下脚本,传送屋激k有挂吗(透视好牌辅助开挂脚本);传送屋激k有挂吗AI智能教程细...
第5分钟透视!欢乐达人葫芦鱼辅... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
太嚣张了!微信小程序加速器,w... 太嚣张了!微信小程序加速器,wepoker辅助是真的假的(透视)开挂辅助神器(有挂方法);无需打开直...
太无语了辅助!开心游戏攻略,免... 太无语了辅助!开心游戏攻略,免费天天贵阳辅助工具(透视插件辅助开挂脚本);是一款可以让一直输的玩家,...
第9分钟透视!开心网辅助工具,... 第9分钟透视!开心网辅助工具,福州十八扑外卦视频(实操分享开挂辅助安装)>>您好:软件加薇13670...
太夸张了!宝宝浙江辅助工具,w... 太夸张了!宝宝浙江辅助工具,wepoker有没有挂(透视)开挂辅助软件(有人有挂);无需打开直接搜索...
太夸张了辅助!九游辅助器,非凡... 太夸张了辅助!九游辅助器,非凡贪玩挂(一分钟带你了解开挂辅助神器);1、不需要AI权限,帮助你快速的...
第三分钟开挂!湖南牵手胡子跑辅... 第三分钟开挂!湖南牵手胡子跑辅助,衢州都莱破解器(信息共享开挂辅助平台) 了解更多开挂安装加(136...
太嚣张了!新漫游免费辅助器,w... 太嚣张了!新漫游免费辅助器,wepoker怎么增加运气(透视)开挂辅助神器(证实有挂) 【无需打开直...