@EqualsAndHashCode(of = "id")

Ostr·2024년 5월 2일

스프링과 JPA

목록 보기
1/4
post-thumbnail

@EqualsAndHashCode

Lombok 라이브러리에서 제공되는 기능으로, 자바 클래스에서 equals()와 hashCode() 메서드를 자동으로 생성해주는 애노테이션이다.

import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        Person person2 = new Person("John", 30);

        System.out.println(person1.equals(person2)); // true
        System.out.println(person1.hashCode() == person2.hashCode()); // true
    }
}

이렇듯 @EqualsAndHashCode 애노테이션은 간편하고 효율적인 방식으로 객체의 동등성과 해시 코드를 구현할 수 있도록 도와준다.

주의할 점

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@EqualsAndHashCode
public class Person {
    private Long id;
    private String name;
    private Address address;

    public Person(Long id, String name) {
        this.id = id;
        this.name = name;
    }
}

@Getter
@Setter
@EqualsAndHashCode
public class Address {
    private Long id;
    private String city;
    private Person resident;

    public Address(Long id, String city) {
        this.id = id;
        this.city = city;
    }
}

코드 예제를 보면 @EqualsAndHashCode 애노테이션만 사용하고 특정 필드를 지정하지 않았기 때문에 Lombok은 모든 필드를 기반으로 equals() 및 hashCode() 메서드를 생성한다. 이 때 Address 클래스와 Person 클래스가 서로를 참조하고 있기 때문에 equals() 메서드에서 무한 루프가 발생할 수 있다.

순환 참조로 인한 무한 루프를 방지하는 방법은 @EqualsAndHashCode(of = "id")

이렇게 id 필드만을 기반으로 equals() 및 hashCode() 메서드를 생성하면 객체의 동등성을 판단할 때 id 값만을 비교하므로 순환 참조로 인한 무한 루프 문제를 방지할 수있다.

0개의 댓글