如何使用@EqualsAndHashCode With Include - Lombok

How to use @EqualsAndHashCode With Include - Lombok

如何将 @EqualsAndHashCodeInclude、Java 的 Lombok 库一起使用。

@EqualsAndHashCode.Include( )

如何让 Equals 比较 class id?

示例:

@EqualsAndHashCode.Include( )
@Table(name = "USER")
public class User
{

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "IDENTITY_USER")
  private Long identity;
}

你应该在球场上使用它,而不是在 class 本身上使用它。您可以通过检查定义以下目标的注释的定义来检查这一点(字段和方法,而不是 class)

@Target({ElementType.FIELD, ElementType.METHOD})

这是一个如何使用它的例子

@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Table(name = "USER")
public class User
{

  @Id
  @EqualsAndHashCode.Include()
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "IDENTITY_USER")
  private Long identity;
}

Include 注释用于要包含在 equalshashCode 方法中的成员。如果您想准确指定应该使用哪些成员(而不是所有 non-static non-transient 成员的默认值),您可以在 @EqualsAndHashCode 注释中使用 onlyExplicitlyIncluded = true 选项:

@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Table(name = "USER")
public class User
{

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "IDENTITY_USER")
  @EqualsAndHashCode.Include
  private Long identity;
}

Lombok 开始,只需在必填字段上添加 @EqualsAndHashCode.Include@EqualsAndHashCode.Exclude

Any class definition may be annotated with @EqualsAndHashCode to let lombok generate implementations of the equals(Object other) and hashCode() methods. By default, it'll use all non-static, non-transient fields, but you can modify which fields are used (and even specify that the output of various methods is to be used) by marking type members with @EqualsAndHashCode.Include or @EqualsAndHashCode.Exclude. Alternatively, you can specify exactly which fields or methods you wish to be used by marking them with @EqualsAndHashCode.Include and using @EqualsAndHashCode(onlyExplicitlyIncluded = true).

@EqualsAndHashCode
@Table(name = "USER")
public class User
  {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "IDENTITY_USER")
  @EqualsAndHashCode.Include
  private Long identity;
 }