Project Lombok @Data Annotation

Imagine you have to write an application which contains a lot of entities.

All these entities have different attritbutes and so on they have setters and getters.
In usual business solution you are also overriding the equals and hashcode methods.

Following an example of a small Customer entity

public class Customer {
    
    private long id;

    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    //Followed by overriden equals and hashcode 

As you can see, just that two parameter id and name create a big load of code.
And the equals and hashcode method are not even displayed in that code snippet.

Exact this is the part where the magic of Project Lombok happens.
Imagine how nice and fantastic it would be if you would just declare your attributes of your entity and you don´t ever have to specify your…

  • …getter
  • …setter
  • …equals
  • …hashcode
  • …constructors
  • …and more…

So let´s move on and implement Project Lombok to our entities.
At first we are going to implement the maven depdendency to Project Lombok in our pom.xml.

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
    <scope>provided</scope>
</dependency>

Now let´s switch back to our Customer.
Delete all the “unnecessary” setter, getter, equals and hashcode.

So now your attributes (in case they are declared as private) are not visible for the rest of your application. But this is just for this moment.
No we will modify the Customer Entity as follow:

import lombok.Data;
/**
 * @author javadevcorner.com
 */
@Data
public class Hero {
    
    private long id;

    private String realName;
}

So now we have done the entire spirit.
The @Data Annotation declares

Java CodeLombok Annotation
Getter and Setter@Getter and @Setter
Equals and Hashcode@EqualsAndHashcode
toString@toString
Contrsuctors@RequiredArgsConstructor

 

So thanks for reading and have fun using Lombok.

Feel free to share

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.