목차
벌크성 수정 쿼리 public int bulkAgePlus (int age) { int resultCount = em.createQuery("update Member m set m.age = m.age + 1 where m.age >= :age" ) .setParameter("age" , age) .executeUpdate(); return resultCount; }
@Test public void bulkUpdate () { memberJpaRepository.save(new Member ("member1" , 10 )); memberJpaRepository.save(new Member ("member2" , 19 )); memberJpaRepository.save(new Member ("member3" , 20 )); memberJpaRepository.save(new Member ("member4" , 21 )); memberJpaRepository.save(new Member ("member5" , 40 )); int resultCount = memberJpaRepository.bulkAgePlus(20 ); assertThat(resultCount).isEqualTo(3 ); }
Spring JPA 사용하기 @Modifying @Query("update Member m set m.age = :age+1 where m.age >= :age") int bulkAgePlus (@Param("age") int age) ;
벌크성 쿼리는 영속성 Context를 무시하고 바로 DB에 업데이트를 진행 시키기 때문에 벌크성 쿼리를 수행한 후에는 영속성 Context를 초기화 해줄 필요가 있다. 안그러면 기존에 남아있는데이터가 꼬여서 문제가 발생할 수 있다.
@Test public void bulkUpdate () { memberRepository.save(new Member ("member1" , 10 )); memberRepository.save(new Member ("member2" , 19 )); memberRepository.save(new Member ("member3" , 20 )); memberRepository.save(new Member ("member4" , 21 )); memberRepository.save(new Member ("member5" , 40 )); int resultCount = memberRepository.bulkAgePlus(20 ); entityManager.flush(); entityManager.clear(); assertThat(resultCount).isEqualTo(3 ); }
@Modifying(clearAutomatically = true) @Query("update Member m set m.age = :age+1 where m.age >= :age") int bulkAgePlus (@Param("age") int age) ;