자바/QueryDsl
[DataJpa] 벌크성 수정 쿼리
OverTheHorizon3410
2023. 11. 17. 22:23
벌크성 수정 쿼리
- 한번의 연산으로 여러 행을 수정하는 쿼리
- JPA 와 스프링 데이타아 JPA 에서 모두 지원한다.
JPA 사용
- 그냥 보고 넘어간다
int bulkPriceUp(String stockAmount) {
String qlString = "update Product p set p.price = p.price * 1.1 where p.stockAmount < :stockAmount";
return em.createQuery(qlString)
.setParameter("stockAmount", stockAmount)
.executeUpdate();
}
- 저런식으로 짜는건 싫다
Data Jpa 사용
@Modifying
@Query(value = "update Item i set i.price = i.price *1.1 where i.stockQuantity < :stockAmount")
int bulkPriceUp(@Param("stockAmount") int stockAmount);
- 일단 price 의 자료형이 float 이거나 double 이여야 한다. 정수값에 1.1 배한 값으로 업데이트가 불가능하기 때문이다.
@Entity
@Getter
@NoArgsConstructor
@ToString
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private float price;
private int stockQuantity;
@Test
void testBulkPriceUp() {
int i = itemRepository.bulkPriceUp(10);
System.out.println("i = " + i);
}
- 재고 10개 이상의 상품에 대해 벌크 업데이트를 수행할 수 있다.
이걸 왜씀?
- 영속성 컨텍스트를 무시하고 바로 데이터베이스에 업데이트 쿼리를 수행할 수 있따.
- 영속성 컨텍스트에 남아있는 엔티티와 DB 상태가 동기화되지 않을 수 있기에,
@Modifying(clearAutomatically = true)
- 속성을 쿼리에 지정하면 벌크 연산후 영속성 컨텍스트를 자동으로 초기화가 가능하다.
@Modifying(clearAutomatically = true)
@Query(value = "update Item i set i.price = i.price *1.1 where i.stockQuantity < :stockAmount")
int bulkPriceUp(@Param("stockAmount") int stockAmount);
Uploaded by N2T