eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll discuss Lombok’s @EqualsAndHashCode annotation, which generates the equals() and hashCode() methods for a class based on its fields.

2. Usage of @EqualsAndHashcode

The @EqualsAndHashCode annotation in Lombok generates the equals() and hashCode() methods for a given class, using all non-static and non-transient fields by default.

To customize the fields used, we can mark them with @EqualsAndHashCode.Include or exclude them with @EqualsAndHashCode.Exclude.

Let’s see an example to understand how it works:

@EqualsAndHashCode
public class Employee {
    private String name;
    private int id;
    private int age;
}

In this example, we’ve defined an Employee class with fields, name, id, and age, and annotated it with @EqualsAndHashCode.

Let’s take a look at the compiled class that includes the equals(), hashCode(), and canEqual() methods generated by Lombok:

public class EmployeeDelomboked {
    private String name;
    private int id;
    private int age;

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

                return false;
            }
        }
    }

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

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

When generating the equals() and hashCode() methods, Lombok also generates a canEqual() method that checks whether the compared object is an instance of the same class as the current object. It ensures that the equals() method proceeds with the comparison only when the objects are of the same class.

3. Excluding Fields From EqualsAndHashCode

Lombok offers several options to exclude specific fields from the method generation process. Let’s take a look at these options.

3.1. Exclude at Field Level With @EqualsAndHashcode.Exclude

We can use the @EqualsAndHashCode.Exclude annotation to instruct Lombok to exclude a field from the generation of equals() and hashCode() methods:

@EqualsAndHashCode
public class Employee {
    private String name;

    @EqualsAndHashCode.Exclude
    private int id;

    @EqualsAndHashCode.Exclude
    private int age;
}

In this example, we used the @EqualsAndHashCode.Exclude annotation to exclude the id and age fields from the equals() and hashCode() method generation. As a result, Lombok won’t use these fields to generate the methods:

public class EmployeeDelomboked {
    //fields names
    //standard getters and setters
    //equals() implementation
    @Override
    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        final Object $name = this.getName();
        result = result * PRIME + ($name == null ? 43 : $name.hashCode());
        return result;
    }
}

We can see that the generated hashCode() method just uses the name field.

3.2. Exclude at Class Level

We can also use @EqualsAndHashCode.Exclude annotation at the class level to exclude the fields:

@EqualsAndHashCode(exclude = {"id", "age"})
public class Employee {
    private String name;
    private int id;
    private int age;
}

In this example, we didn’t annotate the fields directly with @EqualsAndHashCode.Exclude. Instead, we applied the annotation at the class level and specified the field names to exclude. Regardless, the resulting equals() and hashCode() methods will be the same.

4. Including Specific Fields

Now that we’ve learned how to exclude fields, let’s delve into including specific fields in the generation of the equals() and hashCode() methods.

4.1. Include at Field Level

To include specific fields when generating equals() and hashCode() methods, we can use the @EqualsAndHashCode.Include annotation. This annotation typically works in tandem with onlyExplicitlyIncluded=true on the @EqualsAndHashCode annotation:

@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Employee {
    @EqualsAndHashCode.Include
    private String name;
    @EqualsAndHashCode.Include
    private int id;
    private int age;
}

We set onlyExplicitlyIncluded=true attribute and annotated name and id fields with @EqualsAndHashCode.Include. Lombok generates the equals() and hashCode() methods using only these fields. It excludes the age field since it wasn’t marked with @EqualsAndHashCode.Include.

4.2. Include at Method Level

Moreover, we can incorporate the results of custom methods into the equals() and hashCode() methods by annotating them with @EqualsAndHashCode.Include:

@EqualsAndHashCode
public class Employee {
    private String name;
    private int id;
    private int age;

    @EqualsAndHashCode.Include
    public boolean hasOddId() {
        return id % 2 != 0;
    }
}

Here, we have annotated the hasOddId() method with @EqualsAndHashCode.Include, indicating that Lombok should use the result of this method in addition to the fields when generating the equals() and hashCode() methods:

public class EmployeeDelomboked {

    //fields, equals method
    //standard getters and setters
    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        result = result * PRIME + this.getId();
        result = result * PRIME + this.getAge();
        result = result * PRIME + (this.hasOddId() ? 79 : 97);
        final Object $name = this.getName();
        result = result * PRIME + ($name == null ? 43 : $name.hashCode());
        return result;
    }
}

We can see the hashCode() method includes the hasOddId() method.

4.3. Include at Class Level

@EqualsAndHashCode includes an attribute of to define the included fields. In this case, we don’t use any annotations in the fields or methods:

@EqualsAndHashCode(of = {"name", "id"})
public class Employee {
    private String name;
    private int id;
    private int age;
}

Here, we specified the fields name and id to include in the @EqualsAndHashCode annotation by using the of attribute. By doing so, Lombok will use only these fields to generate the equals() and hashCode() methods.

This approach is similar to using @EqualsAndHashCode.Include with onlyExplicitlyIncluded attribute. Lombok actually recommends using onlyExplicitlyIncluded instead. The of attribute is expected to be deprecated in the future.

5. EqualsAndHashCode and Inheritance

When a class extends another class, Lombok’s @EqualsAndHashCode generated methods don’t call the parent class’s equals() and hashCode() methods by default. However, we can include the parent’s class’s equals() and hashCode() in the generation of the child class’s equals() and hashCode() by setting the callSuper attribute to true:

@EqualsAndHashCode(callSuper = true)
public class Manager extends Employee {
    private String departmentName;
    private int uid;
}
public class ManagerDelomboked extends Employee {
    //fields
    //equals implementation

    public int hashCode() {
        final int PRIME = 59;
        int result = super.hashCode();
        result = result * PRIME + this.getUid();
        final Object $departmentName = this.getDepartmentName();
        result = result * PRIME + ($departmentName == null ? 43 : $departmentName.hashCode());
        return result;
    }
}

Here, we can see that the hashCode() method calls the super.hashCode() method.

6. Lombok @EqualsAndHashCode Configuration

To configure the behavior of @EqualsAndHashCode annotation, we need to create a lombok.config file in our project. This file contains configuration keys that can be used to modify the behavior of the generated equals() and hashCode() methods.

6.1. lombok.equalsAndHashCode.doNotUseGetters

lombok.equalsAndHashCode.doNotUseGetters = [true | false] (default: false)

The configuration key lombok.equalsAndHashCode.doNotUseGetters can be set to true or false (default false).

When set to true, Lombok will access fields directly instead of using getters (if available) when generating the equals() and hashCode() methods. However, if the annotation parameter doNotUseGetters is explicitly specified, it takes precedence over this setting.

6.2. lombok.equalsAndHashCode.callSuper

lombok.equalsAndHashCode.callSuper = [call | skip | warn] (default: warn)

The configuration key lombok.equalsAndHashCode.callSuper can be set to call, skip, or warn (default warn).

If set to call, Lombok will include calls to the superclass implementation of hashCode() and equals() when generating these methods for a subclass. If set to skip, no such calls are generated. The default behavior is like skip, but with an additional warning.

6.3. lombok.equalsAndHashCode.flagUsage

lombok.equalsAndHashCode.flagUsage = [warning | error] (default: not set)

Lombok will flag any usage of @EqualsAndHashCode as a warning or error if configured.

7. Advantages and Disadvantages of Using @EqualsAndHashCode Annotation

There are both advantages and disadvantages to using the @EqualsAndHashCode annotation. Let’s take a look at some of them.

7.1. Advantages

Lombok’s @EqualsAndHashCode annotation is a useful technique for simplifying the creation of the equals() and hashCode() methods. It provides customization options, such as excluding fields or using a different hash code algorithm.

7.2. Disadvantages

There are several disadvantages to using Lombok’s @EqualsAndHashCode annotation. First, it can generate unwanted hash code collisions when two objects have different field values but the same hash code.

Second, it may not be compatible with other libraries and frameworks that rely on traditional implementations of equals() and hashCode().

Lastly, it can reduce readability by generating methods that aren’t explicitly defined in the class, making it more difficult to understand the logic of the code.

8. Common Issues

When using Lombok’s @EqualsAndHashCode annotation on classes with bidirectional relationships, such as parent-child relationships, a java.lang.StackOverflowError might occur.

Let’s look at an example of how @EqualsAndHashCode can cause a problem:

@EqualsAndHashCode
public class Employee {
    private String name;
    private int id;
    private int age;
    private Manager manager;
}
@EqualsAndHashCode
public class Manager {
    private String name;
    private Employee assistantManager;
}

In this example, the Employee and Manager classes have a bidirectional relationship and use @EqualsAndHashCode. When an instance of Employee calls its hashCode() method, it will trigger a call to the Manager class’s hashCode() method, which will recursively call back to Employee‘s hashCode() method. This recursive loop will continue until the program runs out of stack space and throws an error.

To avoid this issue, we can use the exclude or onlyExplicitlyIncluded attributes of @EqualsAndHashCode to exclude one of the classes from the generation of the hashCode() and equals() methods. For example, we can exclude the manager field from the hashCode() calculation in the Employee class:

@EqualsAndHashCode(exclude = "manager")
public class EmployeeV2 {
    private String name;
    private int id;
    private int age;
    private Manager manager;
}

9. Conclusion

In this article, we’ve seen how the Lombok @EqualsAndHashCode annotation generates equals() and hashCode() methods. We’ve also explored how inclusion and exclusion on the field and class level can customize the generated methods.

Using the Lombok @EqualsAndHashCode annotation can save time and effort. However, we should be aware of potential issues such as hash code collisions, incompatibility with other libraries, and StackOverflowError in bidirectional relationships.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)