How to use @EqualsAndHashCode With Include - Lombok

36,343

Solution 1

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;
}

Solution 2

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;
}

Solution 3

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;
 }
Share:
36,343
Sérgio Thiago Mendonça
Author by

Sérgio Thiago Mendonça

Updated on July 06, 2020

Comments

  • Sérgio Thiago Mendonça
    Sérgio Thiago Mendonça almost 4 years

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

    @EqualsAndHashCode.Include( )
    

    How to make Equals compare the class id?

    Example:

    @EqualsAndHashCode.Include( )
    @Table(name = "USER")
    public class User
    {
    
      @Id
      @GeneratedValue(strategy = GenerationType.IDENTITY)
      @Column(name = "IDENTITY_USER")
      private Long identity;
    }