Home Lombok Lombok Data annotation examples

Lombok Data annotation examples

In this article we will see what is Lombok Data (@Data) annotation, how it works with your IDE and build tools and how do we use it in java with a basic example.

1. What is Lombok Data annotation

Lombok Data annotation (@Data) Generates getters, for all fields, a useful toString method, and hashCode and equals implementations that check all non-transient fields. Will also generate setters for all non-final fields, as well as a constructor. A @Data annotations Equivalent to combination of @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode.

In other words, @Data generates all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans:

  1. getter methods for all fields,
  2. setter methods for all non-final fields,
  3.  appropriate toString(),
  4. appropriate equals() and
  5. hashCode() implementations that involve the fields of the class,
  6. and a constructor that initializes all final fields,
  7. as well as all non-final fields with no initializer that have been marked with @NonNull, in order to ensure the field is never null.

In the following code, two approaches are equal. @Dataannotation minimizes the usage of more annotations when you need to generate all the above 7 requirements, the are most common for the Pojo classes.

@Getter @Setter 
@RequiredArgsConstructor
@ToString 
@EqualsAndHashCode
public class Employee extends Person {
	
    private Long id;
    private String username;
    private String firstName;
    private String lastName;
    private String email;
    private LocalDate lastUpdated;
    private boolean active;
    
}

Above code equal to the following code.

- Advertisement -
@Data
public class Employee extends Person {
	
    private Long id;
    private String username;
    private String firstName;
    private String lastName;
    private String email;
    private LocalDate lastUpdated;
    private boolean active;
    
}

2. How Lombok Data annotation works

Lombok annotation @Data simply tells to the IDE (either Eclipse or Spring tool Suite or IntelliJ etc) or your build tool like Maven or Ant, to generate all the boilerplate code for you silently during compile time. So that user need not to create this code every time when created fields, developer can access all these methods as usual withing IDE while writing code from the generated .class file.

Let’s have a look into examples without Lombok Data annotation in plain vanilla Java code and with @Data annotation .

2.1. Without @Data annotation

Without Lombok your POJO code looks like :

package com.javabydeveloper.nonlombok;

import java.time.LocalDate;

public class User {
	
    private Long id;
    private String username;
    private String firstName;
    private String lastName;
    private String email;
    private LocalDate lastUpdated;
    private boolean active;
    
    User(){} //default constructor
    
    //All args constructor
	public User(Long id, String username) {
		super();
		this.id = id;
		this.username = username;
	}

	public Long getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public LocalDate getLastUpdated() {
		return lastUpdated;
	}

	public void setLastUpdated(LocalDate lastUpdated) {
		this.lastUpdated = lastUpdated;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", firstName=" + firstName + ", lastName=" + lastName
				+ ", email=" + email + ", lastUpdated=" + lastUpdated + ", active=" + active + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (active ? 1231 : 1237);
		result = prime * result + ((email == null) ? 0 : email.hashCode());
		result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
		result = prime * result + ((lastUpdated == null) ? 0 : lastUpdated.hashCode());
		result = prime * result + ((username == null) ? 0 : username.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (active != other.active)
			return false;
		if (email == null) {
			if (other.email != null)
				return false;
		} else if (!email.equals(other.email))
			return false;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		if (lastUpdated == null) {
			if (other.lastUpdated != null)
				return false;
		} else if (!lastUpdated.equals(other.lastUpdated))
			return false;
		if (username == null) {
			if (other.username != null)
				return false;
		} else if (!username.equals(other.username))
			return false;
		return true;
	} 
}

2.2. With Lombok @Data annotation

If we use Lombok @Data annotation the POJO code looks like below. Final generated .class java byte code files contains code like getters, setters etc like above code, but that code generation will happened at compile time, Lombok library take cares of that, users can get rid of writing all that boiler plate code just by adding @Data annotation to the POJO class. See at following code how much code reduced for the developer in IDE if we use lombok.

package com.javabydeveloper.lombok;

import java.time.LocalDate;

import lombok.Data;

@Data
public class User {
	
    private Long id;
    
    private String username;
    
    private String firstName;
    
    private String lastName;
    
    private String email;
    
    private LocalDate lastUpdated;
    
    private boolean active;
    
}

2.3. Demo

package com.javabydeveloper.lombok;

import java.time.LocalDate;

public class LombokDataAnnotationDemo {

public static void main(String[] args) {
    	
        User user1 = new User();
        user1.setId(1L);
        user1.setFirstName("Peter");
        user1.setLastName("Milanovich");
        user1.setActive(true);
        user1.setUsername("peterm");
        user1.setLastUpdated(LocalDate.now());
        
        System.out.println("Id : "+user1.getId());
        System.out.println("Username : "+user1.getUsername());
        System.out.println("First Name : "+user1.getFirstName());
        
        //toString()
        System.out.println(user1.toString());
        
        //hashcode()
        System.out.println("User1 Hash Code: "+ user1.hashCode());
        
        //to test eqauls()
        User user2 = new User();
        user2.setId(1L);
        user2.setFirstName("Peter");
        user2.setLastName("Milanovich");
        user2.setActive(true);
        user2.setUsername("peterm");
        user2.setLastUpdated(LocalDate.now());
        
        //hashcode()
        System.out.println("User2 Hash Code: "+ user2.hashCode());
        
        System.out.println(user1.equals(user2));
        
    } 
}

Output :

Id : 1
Username : peterm
First Name : Peter
User(id=1, username=peterm, firstName=Peter, lastName=Milanovich, email=null, lastUpdated=2019-12-17, active=true)
User1 Hash Code: -1841038722
User2 Hash Code: -1841038722
User1 and User2 are same? true

Conclusion

We have covered in this article what is Lombok data annotation (@Data), how do we use it in java with a simple example by differentiating with plain Java Pojo class. To setup Lombok in your IDE like Eclipse or STS refer article Lombok Maven Example. Before you use Lombok in your project we strongly recommend try to implement and refer Project Lombok @Data annotation features .

- Advertisement -
Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Also founder of javabydeveloper.com. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories

Related Articles