How to use @EqualsAndHashCode With Include - Lombok

前端 未结 3 1353
Happy的楠姐
Happy的楠姐 2021-02-19 02:42

How to use @EqualsAndHashCode With Include, Lombok library for Java.

@EqualsAndHashCode.Include( )

How to make Equal

相关标签:
3条回答
  • 2021-02-19 03:20

    The Include annotation is used on the member(s) you want to include in the equals and hashCode methods. If you want to specify exactly which members should be used (instead of the default of all non-static non-transient members), you could use the onlyExplicitlyIncluded = true option in the @EqualsAndHashCode annotation:

    @EqualsAndHashCode(onlyExplicitlyIncluded = true)
    @Table(name = "USER")
    public class User
    {
    
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "IDENTITY_USER")
      @EqualsAndHashCode.Include
      private Long identity;
    }
    
    0 讨论(0)
  • 2021-02-19 03:35

    From Lombok, Just add the @EqualsAndHashCode.Include or @EqualsAndHashCode.Exclude on required fields

    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;
     }
    
    0 讨论(0)
  • 2021-02-19 03:36

    You should use it on the field, it's not something to be used on the class itself. You can check this by checking the definition of the annotation which defines the following targets (field and method, not a class)

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

    Here is an example of how to use it

    @EqualsAndHashCode(onlyExplicitlyIncluded = true)
    @Table(name = "USER")
    public class User
    {
    
      @Id
      @EqualsAndHashCode.Include()
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "IDENTITY_USER")
      private Long identity;
    }
    
    0 讨论(0)
提交回复
热议问题