摘要:本文圍繞 MyBatis-Plus 數據操作展開,涵蓋標準數據層 CRUD 與分頁查詢;以及各種的復雜 SQL 查詢;映射匹配(@TableField、@TableName 注解)與 ID 生成策略(@TableId 五種類型及全局配置);多數據批量操作,以及邏輯刪除(標記字段、注解、配置)和樂觀鎖(字段、注解、攔截器)機制,全面介紹 MP 核心數據操作功能。
思維導圖
1. 標準數據層CRUD與分頁查詢
基礎增刪改查
//新增方法 @Testvoid testSave() {User user=new User();user.setId(1L);user.setUsername("tom");userMapper.insert(user);}//刪除方法@Testvoid testDelete(int id) {userMapper.deleteById(id);}//修改方法@Testvoid testUpdateById() {User user=new User();user.setId(1L);user.setUsername("Tom");userMapper.updateById(user);}//根據id查詢數據@Testvoid testGetById(int id) {userMapper.selectById(id);}//查詢全部@Testvoid testGetAll() {List<User> userList = userMapper.selectList(null);System.out.println(userList);}
分頁查詢
1.配置MP攔截器
@Configuration
public class MpConfig {@Beanpublic MybatisPlusInterceptor mpInterceptor(){MybatisPlusInterceptor mpInterceptor=new MybatisPlusInterceptor();mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());return mpInterceptor;}
}
2.分頁查詢業務代碼
//分頁查詢@Testvoid testSelectPage() {int current = 1;int size = 2;IPage page = new Page(current, size);userMapper.selectPage(page,null);System.out.println("當前頁碼值:"+page.getCurrent());System.out.println("每頁顯示數:"+page.getSize());System.out.println("一共多少頁:"+page.getPages());System.out.println("一共多少條:"+page.getTotal());System.out.println("所有記錄數:"+page.getRecords());}
3.開啟MP日志(推薦開啟)
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
返回結果
2. 復雜SQL查詢方法合集(Wrapper)
MyBatisPlus將書寫復雜的SQL查詢條件進行了封裝,使用編程的形式完成查詢條件的組合
1.條件查詢 - 設置查詢條件
//按條件查詢@Testvoid SelectByCondition() {//第一種:間接使用lamda格式按條件查詢QueryWrapper<User> wrapper=new QueryWrapper();//設置條件wrapper.lambda().lt(User::getId,2);List<User> userList1 = userMapper.selectList(wrapper);System.out.println(userList1);//第二種:直接使用lamda格式按條件查詢LambdaQueryWrapper<User> lqWrapper=new LambdaQueryWrapper<User>();//設置條件lqWrapper.lt(User::getId,2);List<User> userList2 = userMapper.selectList(wrapper);System.out.println(userList2);}
2.條件查詢 - 組合條件查詢
//按條件查詢@Testvoid SelectByCondition() {LambdaQueryWrapper<User> lqWrapper1=new LambdaQueryWrapper<User>();//設置條件(并列關系)lqWrapper1.lt(User::getId,3).gt(User::getId,1);//設置條件(或者關系)lqWrapper1.gt(User::getId,3).or().lt(User::getId,1);//使用betweenlqWrapper1.between(User::getAge,16,24);//模糊查詢lqWrapper1.like("userName","o");queryWrapper1.likeLeft("userName","R");queryWrapper1.likeRight("userName","e");}
3.條件查詢 - NULL空值
//按條件查詢 - 動態SQL@Testvoid SelectByCondition() {//模擬查詢請求的數據UserQuery query = new UserQuery();query.setAge(18);query.setId(5L);//null值判定LambdaQueryWrapper<User> lqWrapper = new LambdaQueryWrapper<User>();lqWrapper.gt(query.getAge()!=null,User::getAge,query.getAge());}
4.條件查詢 - 查詢投影
先按設定條件篩選出滿足要求的數據行,再從這些行中提取所需的特定列,最終得到既符合條件限制又僅包含目標字段的數據結果。
查詢投影
//條件查詢 - 查詢投影@Testvoid SelectByCondition() {//寫法一:這種寫法只適用于LambdaLambdaQueryWrapper<User> lqWrapper = new LambdaQueryWrapper<User>();lqWrapper.select(User::getId,User::getAge,User::getUsername);//寫法二:使用兩次查詢QueryWrapper<User> queryWrapper=new QueryWrapper<>();queryWrapper.select("id","userName","age");//若結果為單個對象,使用selectOneList<User> userList = userMapper.selectList(queryWrapper);}
查詢數量,查詢分組
//條件查詢 - 查詢投影@Testvoid SelectByCondition() {//查詢數量QueryWrapper<User> queryWrapper=new QueryWrapper<>();queryWrapper.select("count(*) as count");//按年齡分組queryWrapper.groupBy("age");List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);System.out.println(maps);}
3. 映射匹配兼容性
字段映射與表名映射
使用TableField注解解決
1.value屬性
2.exist屬性
2.select屬性
使用TableName注解
4.id生成策略
使用@TableId注解
總共五大ID生成策略
使用方法
@Data
@TableName(value ="user")
public class User {//五選一@TableId(type = IdType.AUTO)@TableId(type = IdType.ASSIGN_ID)@TableId(type = IdType.NONE)@TableId(type = IdType.INPUT)@TableId(type = IdType.ASSIGN_UUID)private Long id;private String username;private Integer age;private String phone;
}
全局配置方法
全局配置
5.多數據操作 - 刪除和查詢
//批量刪除@Testvoid testDelete() {List<Long> list=new ArrayList<>();for (long i = 1; i < 5; i++) {list.add(i);}userMapper.deleteBatchIds(list);}//批量查詢@Testvoid testDelete() {List<Long> list=new ArrayList<>();for (long i = 1; i < 5; i++) {list.add(i);}userMapper.selectBatchIds(list);}
6.邏輯刪除
1.添加邏輯刪除標記字段
2.實體類加@TableLogic注解
3.修改配置文件
mybatis-plus:global-config:db-config:logic-delete-field: isDeletelogic-delete-value: 1logic-not-delete-value: 0
7.樂觀鎖
1.添加鎖標記字段
2.添加版本注解
3.配置樂觀鎖攔截器實現鎖機制對應的動態SQL語句拼裝
至此,大功告成!🎉🎉🎉