Upon update queries, JPA, by default, operates queries on all the columns of the corresponding entity. Hence, there is a chance of certain columns unintentionally gaining null values because it was not updated.
Specify the value of certain columns explicity when building the entity
아래는 JPA가 정의하는 라이프사이클 이벤트다
@PrePersist
- before persist is called for a new entity@PostPersist
- after persist is called for a new entity@PreRemove
- before an entity is removed@PostRemove
- after an entity is deleted@PreUpdate
- before the update operation@PostUpdate
- after an entity is updated@PostLoad
- after an entity has been loaded@Entity
어노테이션이 쓰인 클래스에 대한 메서드에 쓰이는 어노테이션이다. 테스트에 위 어노테이션이 정의된 메서드가 쓰이면 해당 로그가 출력되는 것을 볼 수 있다
EntityListener 클래스를 정의하여
public class ExampleListener {
@PrePersist
@PreUpdate
@PreRemove
private void beforeAnyUpdate() { ... }
@PostPersist
@PostUpdate
@PostRemove
private void afterAnyUpdate() { ... }
}
엔티티에 적용해서 리스닝!
@EntityListeners(ExampleListener.class)
@Entity
public class ExampleEntity { ... }
엔티티에 적용하는 어노테이션으로, 수정/삽입 작업이 적용된 컬럼만 수정/삽입하도록 설정한다
INSERT
쿼리 시 null
값의 컬럼을 제외하여 쿼리문을 생성한다
쿼리에 걸리는 시간을 줄인다
UPDATE
쿼리 시 null
값의 컬럼을 제외하여 쿼리문을 생성한다
참고
https://www.baeldung.com/jpa-entity-lifecycle-events
https://mangchhe.github.io/jpa/2021/09/06/EntityDynamicQuery/