天天看點

mybatis plus、lombok、swagger常用注解

  • 實體類
@Data    // 生成getter和setter方法
@AllArgsConstructor    // 有參構造器
@NoArgsConstructor    // 無參構造器
@ToString    // toString方法
@Accessors(chain = true)
@TableName("user")    // 指定表名稱
public class User {

    private String id;

    private String name;

    private Integer age;

    private Date bir;

}

# 例如
@TableName("user_tbl")
public class User {

    // 标注在id屬性上,用于映射資料庫中的id
    @TableId(value="id")
    private int id;

    // 标注在屬性上,用于映射資料庫中的屬性
    @TableField(value="bir")
    private Date birthday;

    //标注在屬性上,表示該屬性在資料庫中不存在,則不會映射
    @TableField(exist = false)  
    private String userName;
}      
  • @Accessors(chain = true)詳解
@Accessors(chain = true)  // 為 true 時,對應字段的 setter 方法調用後,會傳回目前對象      
mybatis plus、lombok、swagger常用注解
  • @NonNull
# 檢查參數是否為空
public void nonNullDemo(@NonNull Employee employee, @NonNull Account account) {
    // just do stuff
}

//成員方法參數加上@NonNull注解
public String getName(@NonNull Person p){
    return p.getName();
}

# 等同于
public String getName(@NonNull Person p){
    if(p==null){
        throw new NullPointerException("person");
    }
    return p.getName();
}      
  • @EqualsAndHashCode,​​參考​​
父類實體類中通常設定為@EqualsAndHashCode(callSuper = false)

子類繼承父類後設定為@EqualsAndHashCode(callSuper = true)
用于重寫equals和hashcode方法      
  • @Data
@Data 是 @Getter、 @Setter、 @ToString、 @EqualsAndHashCode 和 @RequiredArgsConstructor 的快捷方式

用@Data(staticConstructor=”methodName”)來生成一個靜态方法,傳回一個調用相應的構造方法産生的對象

# 例如
@Data(staticConstructor = "of")
public class Student {

    @Setter(AccessLevel.PROTECTED)
    @NonNull
    private String name;

    private Integer age;
}

# 等同于
package com.cauchy6317.common.Data;

import lombok.NonNull;

public class Student {
    @NonNull
    private String name;
    private Integer age;

    private Student(@NonNull String name) {
        if (name == null) {
            throw new NullPointerException("name is marked non-null but is null");
        } else {
            this.name = name;
        }
    }

    public static Student of(@NonNull String name) {
        return new Student(name);
    }

    @NonNull
    public String getName() {
        return this.name;
    }

    public Integer getAge() {
        return this.age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof Student)) {
            return false;
        } else {
            Student other = (Student)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                Object this$name = this.getName();
                Object other$name = other.getName();
                if (this$name == null) {
                    if (other$name != null) {
                        return false;
                    }
                } else if (!this$name.equals(other$name)) {
                    return false;
                }

                Object this$age = this.getAge();
                Object other$age = other.getAge();
                if (this$age == null) {
                    if (other$age != null) {
                        return false;
                    }
                } else if (!this$age.equals(other$age)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof Student;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $name = this.getName();
        int result = result * 59 + ($name == null ? 43 : $name.hashCode());
        Object $age = this.getAge();
        result = result * 59 + ($age == null ? 43 : $age.hashCode());
        return result;
    }

    public String toString() {
        return "Student(name=" + this.getName() + ", age=" + this.getAge() + ")";
    }

    protected void setName(@NonNull String name) {
        if (name == null) {
            throw new NullPointerException("name is marked non-null but is null");
        } else {
            this.name = name;
        }
    }
}      
  • @Value
@Value注解會把所有成員變量預設定義為private final修飾,并且不會生成set方法
等同于@Getter、@ToString、@EqualsAndHashCode、@RequiredArgsConstructor      
  • @Buidler
public class Car {
    private String make;
    private String model;
    private String bodyType;
    private int yearOfManufacture;
    private int cubicCapacity;
    private List<LocalDate> serviceDate;
}

# 使用該注解時,建構1個對象
Car muscleCar = Car.builder().make("Ford")
        .model("mustang")
        .bodyType("coupe")
        .build();      
  • @With
# 例如
public class User {
    private final String username;
    private final String emailAddress;
    @With
    private final boolean isAuthenticated;

    //getters, constructors
}

public class User {
    private final String username;
    private final String emailAddress;
    private final boolean isAuthenticated;

    //getters, constructors

    public User withAuthenticated(boolean isAuthenticated) {
        return this.isAuthenticated == isAuthenticated ? this : new User(this.username, this.emailAddress, isAuthenticated);
    }
}

User immutableUser = new User("testuser", "[email protected]", false);
User authenticatedUser = immutableUser.withAuthenticated(true);

assertNotSame(immutableUser, authenticatedUser);
assertFalse(immutableUser.isAuthenticated());
assertTrue(authenticatedUser.isAuthenticated());      
  • @Cleanup
# 這個注解用在變量前面,可以保證此變量代表的資源會被自動關閉,預設是調用資源的close()方法,如果該資源有其它關閉方法,可使用@Cleanup(“methodName”)來指定要調用的方法

# 例如
public static void main(String[] args) throws IOException {
     @Cleanup InputStream in = new FileInputStream(args[0]);
     @Cleanup OutputStream out = new FileOutputStream(args[1]);
     byte[] b = new byte[1024];
     while (true) {
       int r = in.read(b);
       if (r == -1) break;
       out.write(b, 0, r);
     }
 }      
  • @RequiredArgsConstructor
使用類中所有帶有@NonNull注解的或者帶有final修飾的成員變量生成對應的構造方法,成員變量都是非靜态的

如果類中含有final修飾的成員變量,是無法使用@NoArgsConstructor注解的

用@RequiredArgsConstructor(staticName=”methodName”)的形式生成一個指定名稱的靜态方法,傳回一個調用相應的構造方法産生的對象

# 例如
@RequiredArgsConstructor(staticName = "sunsfan")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
@NoArgsConstructor
public class Shape {
    private int x;
    @NonNull
    private double y;
    @NonNull
    private String name;
}

# 等同于
public class Shape {
    private int x;
    private double y;
    private String name;

    public Shape(){
    }

    protected Shape(int x,double y,String name){
        this.x = x;
        this.y = y;
        this.name = name;
    }

    public Shape(double y,String name){
        this.y = y;
        this.name = name;
    }

    public static Shape sunsfan(double y,String name){
        return new Shape(y,name);
    }
}      
  • @SneakyThrows
# 将方法中的代碼用try-catch語句包裹起來
# 捕獲異常并在catch中用Lombok.sneakyThrow(e)把異常抛出
# 可以使用@SneakyThrows(Exception.class)的形式指定抛出哪種異常

# 例如
public class SneakyThrows implements Runnable {
    @SneakyThrows(UnsupportedEncodingException.class)
    public String utf8ToString(byte[] bytes) {
        return new String(bytes, "UTF-8");
    }

    @SneakyThrows
    public void run() {
        throw new Throwable();
    }
}

# 等同于
public class SneakyThrows implements Runnable {
    @SneakyThrows(UnsupportedEncodingException.class)
    public String utf8ToString(byte[] bytes) {
        try{
            return new String(bytes, "UTF-8");
        }catch(UnsupportedEncodingException uee){
            throw Lombok.sneakyThrow(uee);
        }
    }

    @SneakyThrows
    public void run() {
        try{
            throw new Throwable();
        }catch(Throwable t){
            throw Lombok.sneakyThrow(t);
        }
    }
}      
  • @Synchronized
# 例如
public class Synchronized {
    private final Object readLock = new Object();

    @Synchronized
    public static void hello() {
        System.out.println("world");
    }

    @Synchronized
    public int answerToLife() {
        return 42;
    }

    @Synchronized("readLock")
    public void foo() {
        System.out.println("bar");
    }
}

# 等同于
public class Synchronized {
   private static final Object $LOCK = new Object[0];
   private final Object $lock = new Object[0];
   private final Object readLock = new Object();

   public static void hello() {
     synchronized($LOCK) {
       System.out.println("world");
     }
   }

   public int answerToLife() {
     synchronized($lock) {
       return 42;
     }
   }

   public void foo() {
     synchronized(readLock) {
       System.out.println("bar");
     }
   }
 }      
  • @Slf4j
依賴 + 插件 + 注解 + log.info()      
  • 實體
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="TestInfo對象", description="實體類詳情")    // knife4j注解
@TableName("test_info")
public class TestInfo implements Serializable {

    private static final long serialVersionUID = 1l;

    @TableId(value = "id", type = IdType.ASSIGN_UUID)    // 自動生成不含中劃線的 UUID 作為主鍵
    private String id;

    @TableField(fill = FieldFill.INSERT)    // MyBatis-Plus設定自動填充時間
    private Date created;

    @TableField(fill = FieldFill.INSERT_UPDATE)    // 自動更新時間
    private Date updated;

    @TableField(value="deleted")
    private Integer deleted;

    @ApiModelProperty(value = "test_id")    // knife4j注解
    @TableField(value="test_id")
    private String testId;

}      
  • 接口
@GetMapping(value = "/getAll")
@ApiOperation(value="接口标題")
@ApiImplicitParams({
        @ApiImplicitParam(name="testDTO",value="測試dto",dataType = "TestDTO",required = true),
})
@ApiResponses({
        @ApiResponse(code = 200, message = "ok", response = TestInfo.class)
})
public JSONResult getAll(TestDTO testDTO){
    IPage<TestInfo> all = testInfoService.getAll(testDTO);
    return new JSONResult(all);
}      
  • 主鍵政策
public class User implements Serializable {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private Date birthday;
}

ASSIGN_ID(雪花算法)
ASSIGN_UUID(排除中劃線的UUID)
AUTO(資料庫ID自增)
INPUT(插入前自行設定主鍵值)
NONE(無狀态)