mybatis-plus 查詢+刪除功能


查詢

最簡單例子
User user = userMapper.selectById(1L);
查詢多個

List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
        users.forEach(System.out::println);

條件查詢

@Test//條件查詢 使用Map
    void test2(){
        HashMap<String,Object> map=new HashMap<>();
        //自定義查詢
        map.put("name","Tom");
        map.put("age",28);
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);
    }

分頁查詢

注冊組件

@Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }

測試功能

@Test
    void test3(){
        //測試分頁查詢
        Page<User> page = new Page<>(2,5);//5條記錄為單位的第二頁
        userMapper.selectPage(page,null);
        page.getRecords().forEach(System.out::println);
    }

結果只有一條ID為6的記錄 符合情況

刪除功能

幾乎和查詢一致
最簡單方法
userMapper.deleteById(1L);
刪除一系列
userMapper.deleteBatchIds(Arrays.asList(1,2,3));
條件刪除
和查詢一樣

邏輯刪除

邏輯刪除指刪除某一條數據時並沒有真的刪除它,而是通過一個變量值的狀態讓它失效

測試邏輯刪除:
添加一個deleted字段 為1時表明被邏輯刪除
實體類添加屬性

@TableLogic//邏輯刪除字段注解
    private Integer deleted;

配置application.yml(不配置也可以 按人家的默認值走)

mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: flag  # 全局邏輯刪除的實體字段名(since 3.3.0,配置后可以忽略不配置步驟2)
      logic-delete-value: 1 # 邏輯已刪除值(默認為 1)
      logic-not-delete-value: 0 # 邏輯未刪除值(默認為 0)

測試刪除

void test1(){
        userMapper.deleteById(1L);
    }

id1數據並沒有刪除 而是被標記為deleted=1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM