본문 바로가기
server

어째서 엔티티가 계속 업데이트 되는가..

by Younji! 2019. 6. 28.

 

트랜잭션이 끝날 때마다 엔티티가 계속 업데이트가 되는데 어째서죠. 조회만 했을 뿐인데요.

그 것은 Converter를 사용하는 필드에서 Section을 새로 매핑해주면서 항상 다른 객체로 인식되었기 때문.. 

@Getter
@Setter
@Entity
@Table
public class Entity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Convert(converter = SectionConverter.class)
    private List<Section> sections;

}

아래에 Section을 보면 EqualsAndHashCode를 따로 선언해주지 않아 매 번 그 객체가 항상 다른 객체로 확인이 되기 때문에 JPA 에서 조회를 할 때마다 (@Transactional 이 묶여있는) 업데이트가 발생했던 것.. 😨

@Getter
@Setter
@NoArgsConstructor
public class Section {
    private Double min;
    private Double max;
    private double cost;

    public boolean contain(double compare) {
        if (min != null && max != null) {
            return min <= compare && max > compare;
        }

        return min <= compare;
    }

    public Section(Double min, Double max, double cost) {
        this.min = min;
        this.max = max;
        this.cost = cost;
    }
}

필드에 매핑된 데이터가 같으면 동등해야 하기 때문에 추가했습니다.

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Section that = (Section) o;
        return Double.compare(that.cost, cost) == 0 &&
            Objects.equals(min, that.min) &&
            Objects.equals(max, that.max);
    }

    @Override
    public int hashCode() {
        return Objects.hash(min, max, cost);
    }

매우 소소하지만 놓쳤던 부분.!

'server' 카테고리의 다른 글

tcpdump mtr  (0) 2020.05.15
모든 API 엔드포인트에 공통 파라미터가 필요하다.  (0) 2020.04.30
fluentd와 함께하는 검색 데이터 수집  (0) 2019.06.26
Redisson  (0) 2019.06.26
ModelMapper  (0) 2019.06.25

댓글