天天看點

mybatis-plus學習與實踐(三)邏輯删除

在我們日常開發中,為了保留資料,經常會使用邏輯删除的方式進行資料删除,而mybatis-plus正好也提供了這一功能,在第一節中生成代碼的時候,我們指定了邏輯删除字段的值,代碼如下:

StrategyConfig sc = new StrategyConfig();
        sc.setCapitalMode(false); //是否大寫命名 預設false
        sc.setSkipView(true); //是否跳過試圖 預設false
        sc.setNaming(NamingStrategy.underline_to_camel);// 表映射 駝峰命名
        sc.setColumnNaming(NamingStrategy.underline_to_camel); // 字段映射 駝峰
        sc.setEntityLombokModel(true); //預設false
        sc.setRestControllerStyle(true); // 預設false
        sc.setEntitySerialVersionUID(true); //預設true
        sc.setEntityColumnConstant(true); //預設false
        sc.setInclude("student"); //表名,用,隔開  需要生産
   //     sc.setExclude(""); //                 不需要生成  二選一
        sc.setEntityTableFieldAnnotationEnable(true); // 預設false 注釋
        sc.setControllerMappingHyphenStyle(false); //預設false
        sc.setLogicDeleteFieldName("status"); // 邏輯删除字段名稱
        generator.setStrategy(sc);
           

我們将status指定為邏輯删除字段,接下來我們看看生成的實體類,發現生成實體的時候在status上多了一個注解@TableLogic,這個注解就是把這個字段辨別為邏輯删除。

@Data
    @EqualsAndHashCode(callSuper = false)
    @Accessors(chain = true)
    @TableName("student")
    @ApiModel(value="Student對象", description="")
    public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.ID_WORKER_STR)
    private String id;

    @TableField("age")
    private Integer age;

    @TableField("name")
    private String name;

    @TableField("tel")
    private String tel;

    @TableField("father_name")
    private String fatherName;

    @ApiModelProperty(value = "1:正常;-1:删除")
    @TableField("status")
    @TableLogic
    private Integer status;
           

然後再看看properties.yml檔案

mybatis-plus:
  global-config:
    db-config:
      logic-delete-value: -1 #邏輯已删除值(預設為1)
      logic-not-delete-value: 1 #邏輯未删除值(預設為0)
           

status=-1為删除,status=1為正常。接下來測試下效果

@Test
   public void studentDelete(){

       int i = studentMapper.deleteById("1");
       System.out.println(i+"------------------/n");
   }

   @Test
   public void studentDeletes(){

       boolean b = studentService.removeById("1");
       System.out.println(b);
   }
           

測試後發現,在service和mapper中的删除方法都可以删除。

注:1、本文所用到的mybatis-plus版本是3.1.1。

2、在測試過程中發現自定義的邏輯删除值并沒有生效,經過在官網上查找了一番,才發現是配置檔案中的key值寫錯了。是以,能複制的盡量别用手敲了。

繼續閱讀