기록

211220 공부 기록

vivi 2021. 12. 20. 05:22

1. Spring data JPA의 @Modifying

https://docs.spring.io/spring-data/data-jpa/docs/current/api/org/springframework/data/jpa/repository/Modifying.html

 

Modifying (Spring Data JPA 2.6.0 API)

Indicates a query method should be considered as modifying query as that changes the way it needs to be executed. This annotation is only considered if used on query methods defined through a Query annotation. It's not applied on custom implementation meth

docs.spring.io

https://www.baeldung.com/spring-data-jpa-modifying-annotation

 

@Modifying 어노테이션은 @Query 어노테이션에서 조회 쿼리, 즉 select 문을 제외한 insert, update, delete, ddl 문을 작성할 때 필요하다.

@Modifying 어노테이션없이 @Query로 변경, 삭제 등의 쿼리를 사용하면 nvalidDataAccessApiUsage exception이 발생한다.

@Modifying @Query는 JPA Entity LifeCycle을 무시하고 쿼리가 실행되므로 영속성 컨텍스트 관리에 주의해야한다.

즉, @Modifying 어노테이션을 사용하여 벌크 연산 Query를 실행하면 DB에는 반영되지만, 영속성 컨텍스트에 캐시되어 있을 경우 캐시에는 쿼리 결과가 반영되어있지 않다. 이것을 해결하기 위해 영속성 컨텍스트를 clear하면되는데, 아래 clearAutomatically 옵션을 사용하면된다. 추가로, flushAutomatically는 아직 flush되지 않은 결과가 있을 때 사용한다.

// the persistence context is cleared after our query execution.
// persistence context will fetch the entities from the database next time.
@Modifying(clearAutomatically = true)
// However, if our persistence context contained unflushed changes, clearing it would mean dropping the unsaved changes.
// Fortunately, there's another property of the annotation we can use in this case, flushAutomatically:
@Modifying(flushAutomatically = true)