2016-08-22 4 views
1

최대 절전 모드로 데이터베이스에 여러 레코드를 저장하는 데 어려움을 겪고 있습니다. 세션을 열거 나 트랜잭션을 수동으로 시작하지 않으며 가능하면 그렇게하지 않는 것이 좋습니다. 내 서비스 클래스는 다음과 같습니다최대 절전 모드 - 하나의 트랜잭션에 여러 개체 저장

지금
@Service 
@Transactional 
public class OrderServiceImpl implements OrderService { 
    @Autowired 
    private ProductRepository productRepository; 
    @Autowired 
    private OrderRepository orderRepository; 
    @Autowired 
    private CartService cartService; 
    @Autowired 
    private OrderDetailsRepository orderDetailsRepository; 


... 

public void saveOrder(Order order) { 
     Cart cart=order.getCart(); 
     order.setTotalPrice(cart.getGrandTotal()); 
     OrderDetails od = new OrderDetails(); 
     od.setOrder(order); 

     for (Map.Entry<Integer, CartItem> entry : cart.getCartItems().entrySet()) 
     { 
      Product product = entry.getValue().getProduct(); 
      od.setProduct(product); 
       od.setQuantity(entry.getValue().getQuantity()); 
      od.setUnitPrice(product.getUnitPrice()); 
      orderDetailsRepository.save(od); 
     } 

     cartService.delete(order.getCart().getCartId()); 
    } 
... 

} 

, 내가 저장 방법 실행할 때마다, 난 것 같아요 (이 마지막 항목을 저장하지만 현재 상태로, 데이터베이스에 하나 개의 레코드를 저장하려면이 거래 만 커밋 끝에는 SQL 출력 :

Hibernate: 
    insert 
    into 
     Orders 
     (CustomerID, OrderDate, ShippingDate, TotalPrice) 
    values 
     (?, ?, ?, ?) 
Hibernate: 
    insert 
    into 
     OrderDetails 
     (OrderID, ProductID, Quantity, UnitPrice) 
    values 
     (?, ?, ?, ?) 
Hibernate: 
    update 
     OrderDetails 
    set 
     OrderID=?, 
     ProductID=?, 
     Quantity=?, 
     UnitPrice=? 
    where 
     OrderDetailsID=? 

내 저장소 클래스는 persist 메소드를 호출하는 것 외에는 아무 것도하지 않습니다.

Transactional annotation을 사용하는 동안 Hibernate에서 여러 레코드를 데이터베이스에 저장할 수 있습니까? 내 서비스 클래스에서이 주석을 유지하고 싶습니다.

답변

1

시도 carItems 루프에 OrderDetails의 선언을 이동 :

public void saveOrder(Order order) { 
     Cart cart=order.getCart(); 
     order.setTotalPrice(cart.getGrandTotal()); 

     for (Map.Entry<Integer, CartItem> entry : cart.getCartItems().entrySet()) 
     { 
      OrderDetails od = new OrderDetails(); 
      od.setOrder(order); 

      Product product = entry.getValue().getProduct(); 
      od.setProduct(product); 
      od.setQuantity(entry.getValue().getQuantity()); 
      od.setUnitPrice(product.getUnitPrice()); 
      orderDetailsRepository.save(od); 
     } 

     cartService.delete(order.getCart().getCartId()); 
    } 
... 

} 

을 원래 코드에서 어떤 최대 절전 모드가하는 것은 :

첫 번째 반복에서
  • 는 루프 전에 선언했다 OrderDetails 엔티티를 저장 (id를 생성 함)
  • 그 밖의 반복마다 동일한 기존 엔티티 (첫 번째 반복에서 삽입 됨)를 업데이트합니다.

별도의 엔티티 인스턴스를 별도의 db 레코드로 유지하려면 엔티티 인스턴스가 필요합니다.

+0

와우, 어떤 차이가 있는지 모르겠지만 작동합니다. :) –

+0

나는 내 대답을 편집 했으므로 그 질문에 약간의 빛이 들어 왔으면 좋겠다. –

+0

다시 한번 고맙다. :) –