@DynamicUpdate를 사용해야 할까?

Alex·2025년 1월 7일
0

Plaything

목록 보기
68/118

프로필은
업데이트할 때마다 변경되는 부분이 있고 그렇지 않은 부분들이 있다.

만약 변경감지를쓰면 sql쿼리에는 엔티티의 모든 칼럼이 포함된다.

성능을 위해서라면 그대로 사용하는 게 좋고, 엔티티 필드 수는 많은데 한번에 수정해야 할 필드가 적다면(+ 다른 컬럼이 변경되는 것에 대한 우려가 있다면) @DynamicUpdate를 쓰는 게 좋다고 한다.

그러면 변경되는 칼럼만 UPDATE SQL에 넣을 수 있다.

baeldung에 따르면

Actually, when we use @DynamicUpdate on an entity, Hibernate does not use the cached SQL statement for the update. Instead, it will generate a SQL statement each time we update the entity. This generated SQL includes only the changed columns.

In order to find out the changed columns, Hibernate needs to track the state of the current entity. So, when we change any field of an entity, it compares the current and the modified states of the entity.
This means that @DynamicUpdate has a performance overhead associated with it. Therefore, we should only use it when it’s actually required.

Certainly, there are a few scenarios where we should use this annotation — for example, if an entity represents a table that has a large number of columns and only a few of these columns are required to be updated frequently. Also, when we use version-less optimistic locking, we need to use @DynamicUpdate.

DynamicUpdate를 쓰면 JPA가
캐싱해둔 UPDATE SQL을 사용하지 않고 엔티티를 업데이트할 때마다 SQL을 새로 만든다고 한다(변경된 칼럼만 포함된)

이때
하이버네이트가 현재 엔티티의 상태와 변경될의 변화를 추적하고, 이로 인해서 오버헤드가 발생할 수 있다.

DynamicUpdate는 칼럼이 많지만 그 중 일부만 자주 변경될 때 이 어노테이션을 쓰는 게 좋을 거 같다.

지금은 굳이 DynamicUpdate를 사용할 이유가 없어 보인다.

JPA의 캐싱

참고로 JPA는 애플리케이션 로딩 시점에 엔티티에 맞춰서 PrepareStatement 스타일의 SQL Update 구문을 만들고 캐싱한다.

?로 표현된 파라미터 부분만 변경하는 식으로 업데이트 쿼리 사용해서 효율성을 높인다.

성능만 생각하면 SQL에 모든 칼럼이 다 포함되는 것이나,
DynamicUpdate를 사용해서 변경되는 칼럼만 포함시키는 것이나 크게 차이나지 않는다.

영한샘이 한 말인데 자잘한 성능보다는 유지보수가 더 중요할 때가 있는 것 같다.

profile
답을 찾기 위해서 노력하는 사람

0개의 댓글