How to use the @EqualsAndHashCode annotation in SpringBoot?

In Spring Boot, the @EqualsAndHashCode annotation can be used to automatically generate the equals() and hashCode() methods. This annotation can be applied at the class level to automatically generate the equals() and hashCode() methods based on the fields defined in the class.

A simple example of using the @EqualsAndHashCode annotation:

import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class User {
    private String name;
    private int age;
    // 省略构造函数、getter和setter等

    // 在此处可以省略equals和hashCode方法的实现
}

In the example above, the equals() and hashCode() methods in the User class will be generated based on the name and age fields in the class. You can use the exclude attribute of the @EqualsAndHashCode annotation to exclude certain fields, or use the of attribute to specify which fields to include. For example, if you want to exclude the age field, you can use the exclude attribute.

@EqualsAndHashCode(exclude = "age")
public class User {
    private String name;
    private int age;
    // 省略构造函数、getter和setter等

    // 在此处可以省略equals和hashCode方法的实现
}

If you only want to generate the equals() and hashCode() methods based on the name field, you can use the of attribute.

@EqualsAndHashCode(of = "name")
public class User {
    private String name;
    private int age;
    // 省略构造函数、getter和setter等

    // 在此处可以省略equals和hashCode方法的实现
}

By using the @EqualsAndHashCode annotation, code can be streamlined and the equals() and hashCode() methods will automatically update when the fields in the class change.

广告
Closing in 10 seconds
bannerAds