Springboot(十三)——整合mybatis-plus(三)
阿新 • • 發佈:2021-07-02
查詢操作
根據ID查詢使用者
//根據ID查詢使用者
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
批量查詢
@Test public void testSelectByBatchId(){ List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3)); users.forEach(System.out::println); }
條件查詢
@Test public void testSelectByBatchIds(){ HashMap<String, Object> map = new HashMap<>(); //自定義條件查詢,查詢name=zhangsan並且age=19的使用者 map.put("name","zhangsan"); map.put("age",19); List<User> users = userMapper.selectByMap(map); users.forEach(System.out::println); }
分頁查詢操作
分頁在網站使用十分之多!
- 1、原始的limit進行分頁
- 2、pageHelper第三方外掛
- 3、Mybatis-plus內建外掛
編寫mybatis-plus配置類
// 最新版 @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2)); return interceptor; }
編寫測試類
//測試分頁查詢
@Test
public void testPage(){
//引數一:第一頁 引數二:頁面顯示5條資料
Page<User> page = new Page<>(1,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
測試結果
刪除操作
通過ID刪除
@Test
public void testDeleteById(){
userMapper.deleteById("1410758327595810819L");
}
控制檯輸出
檢視資料庫
批量刪除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1410758327595810818L,7L,6L));
}
控制檯輸出
檢視資料庫
條件刪除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","zhangsan2");
userMapper.selectByMap(map);
}
控制檯輸出
檢視資料庫
邏輯刪除
官方文件:https://mp.baomidou.com/guide/logic-delete.html物理刪除:從資料庫中直接移除
邏輯刪除:在資料庫中沒有被移除,而是通過一個變數來讓他失效!deleted = 0 or deleted = 1
管理員可以檢視被刪除的記錄!防止資料丟失,類似於回收站
1、在資料庫中新增一個deleted欄位
2、在實體類中新增屬性
@TableLogic //邏輯刪除註解
private Integer deleted;
3、配置
特別注意:mybatis-plus 3.3版本之後,不需要配置application配置檔案,直接使用註解即可!不然會報錯
mybatis-plus 3.3版本以上自行忽略一下配置
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag # 全域性邏輯刪除的實體欄位名(since 3.3.0,配置後屬性可以不用添加註解)
logic-delete-value: 1 # 邏輯已刪除值(預設為 1)
logic-not-delete-value: 0 # 邏輯未刪除值(預設為 0)
測試
控制檯輸出
檢視資料庫