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 examples.

Make sure you already installed Lombok setup for your IDE. To Setup in Eclipse or in Spring Tool Suite refer to our Lombok Maven example + setup with Eclipse.

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.

lombok data annotation @Data

2. Lombok @Data example

Following side by side code demonstrates simple usage of Lombok’s @Data annotation and how looks like Lombok generated code exactly when you use @Data annotation.

Lomboked User1.java

@Getter @Setter 
@RequiredArgsConstructor
@ToString 
@EqualsAndHashCode
public class User1 {

	private Long id;
	private String username;
	
}

Lomboked User2.java

@Data
public class User2 {

	private Long id;
	private String username;
	
}

Now let’s have a look into Lombok generated (Delomboked) code for both classes.

DeLomboked User1.java

public class User1 {
	private Long id;
	private String username;

	public Long getId() {
		return this.id;
	}

	public String getUsername() {
		return this.username;
	}

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

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

	public User1() {
	}

	@Override
	public String toString() {
		return "User1(id=" + this.getId() + ", username=" + this.getUsername() + ")";
	}

	@Override
	public boolean equals(final Object o) {
		if (o == this)
			return true;
		if (!(o instanceof User1))
			return false;
		final User1 other = (User1) o;
		if (!other.canEqual((Object) this))
			return false;
		final Object this$id = this.getId();
		final Object other$id = other.getId();
		if (this$id == null ? other$id != null : !this$id.equals(other$id))
			return false;
		final Object this$username = this.getUsername();
		final Object other$username = other.getUsername();
		if (this$username == null ? other$username != null : !this$username.equals(other$username))
			return false;
		return true;
	}

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

	@Override
	public int hashCode() {
		final int PRIME = 59;
		int result = 1;
		final Object $id = this.getId();
		result = result * PRIME + ($id == null ? 43 : $id.hashCode());
		final Object $username = this.getUsername();
		result = result * PRIME + ($username == null ? 43 : $username.hashCode());
		return result;
	}
}

DeLomboked User2.java

public class User2 {
	private Long id;
	private String username;

	public User2() {
	}

	public Long getId() {
		return this.id;
	}

	public String getUsername() {
		return this.username;
	}

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

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

	@Override
	public boolean equals(final Object o) {
		if (o == this)
			return true;
		if (!(o instanceof User2))
			return false;
		final User2 other = (User2) o;
		if (!other.canEqual((Object) this))
			return false;
		final Object this$id = this.getId();
		final Object other$id = other.getId();
		if (this$id == null ? other$id != null : !this$id.equals(other$id))
			return false;
		final Object this$username = this.getUsername();
		final Object other$username = other.getUsername();
		if (this$username == null ? other$username != null : !this$username.equals(other$username))
			return false;
		return true;
	}

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

	@Override
	public int hashCode() {
		final int PRIME = 59;
		int result = 1;
		final Object $id = this.getId();
		result = result * PRIME + ($id == null ? 43 : $id.hashCode());
		final Object $username = this.getUsername();
		result = result * PRIME + ($username == null ? 43 : $username.hashCode());
		return result;
	}

	@Override
	public String toString() {
		return "User2(id=" + this.getId() + ", username=" + this.getUsername() + ")";
	}
}

 @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 above code, two approaches are equal. @Dataannotation minimizes the usage of more annotations when you need to generate all the above 7 requirements, they are most common for the Pojo classes.

3. 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 within IDE while writing code from the generated .class file. Users can get rid of writing all that boiler plate code just by adding @Data annotation to the POJO class.

4. staticConstructor

If you specify a staticConstructor name, then the generated constructor will be private, a static factory method is created to that other classes can use to create instances.

Lomboked User3.java

@Data(staticConstructor = "create")
public class User3 {

	private Long id;

	private String username;

}

DeLomboked User3.java

public class User3 {
	private Long id;
	private String username;

	private User3() {
	}

	public static User3 create() {
		return new User3();
	}

     // Rest of code same as delomboked User3.java
}

5. Lombok @Data ignore/exclude fields

@Data annotation alone not provide support for ignoring fields from generating getters/setters or toString or equals and hashCode methods. Following example demonstrates how to exclude fields when you are using @Data annotation.

@Data
public class User4 {

	@Setter(value = AccessLevel.NONE)
	private Long id;

	@Getter(value = AccessLevel.NONE)
	private String username;
	
	@ToString.Exclude
	private boolean active;
	
	@EqualsAndHashCode.Exclude
	@ToString.Exclude
	private int role;

}

6. Lombok @Data and @Builder together

If you use @Data annotation alone, public required-args constructor is generated. If you are using @Data and @Builder annotations together, all-args constructor (Package access level) is generated. In case initializing objects is responsible for third party libraries like Spring Framework, most of the cases they look for no-args constructor.

Following example demonstrates how you can generate all-args and no-args constructor when you are using @Data and @Builder together.

@AllArgsConstructor(access = AccessLevel.PACKAGE)
@NoArgsConstructor
@Data @Builder
public class User5 {

	private Long id;

	private String username;
}

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 lombok generated code. You can refer Delombok Maven example to see how looks like lombok generated code for your Lomboked classes.

Lombok being a matured tool with huge adoption, it saves a significant amount of development time by generating commonly used boiler plate code for POJOs, but it tightly depends on java compiler for annotation processing, you must be aware that upgrading your compiler might break your code.

You can checkout source code at our github repository.

You might be interested in our other following Lombok Tutorials :

  1. Lombok @Getter @Setter and lazy getters
  2. Lombok @ToString
  3. Lombok @EqualsAndHashCode
  4. Lombok @AllArgsConstructor
  5. Lombok @NoArgsConstructor
  6. Lombok @RequiredArgsConstructor
  7. Lombok @NonNull
  8. Lombok @Value
  9. Lombok @Builder
  10. Lombok @Slf4j
  11. Lombok @Singular
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. Follow him on LinkedIn or Twitter or Facebook

1 COMMENT

  1. Hi Satish Varma,

    You did an excellent job on this post! I’d like to add a quick note if you don’t mind?

    We can’t create a User2 object as User2 z = new User2(10, “Linda”) because there is no field on User2 class that is “required”.

    To make sure that @Data generates a required constructor, we need to mark id and username with @NonNull or final.

    Have a great day,

    Abderrahim

Comments are closed.

Stay in Touch

Subscribe

Subscribe for latest updates.

 

Loading

Categories