2016-08-22 7 views
1

Hibernateを使用して複数のレコードをデータベースに保存しようとしています。私はセッションを開いたり、トランザクションを手動で開始したりすることはありません。可能な場合は、これをやめてください。私のサービスクラスは次のようになります。今Hibernate - 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()); 
    } 
... 

} 

、私はsaveメソッドを実行毎回、私はデータベースに1件のレコードを保存したいのですが、しかし、現在の状態でそれが唯一の最後の項目が保存されます(私はそれが唯一のトランザクションをコミット推測最後に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=? 

私のリポジトリクラスは、永続メソッドを呼び出す以外に何もしません。

Transactionalアノテーションを使用しているときに、複数のレコードを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()); 
    } 
... 

} 

、何Hibernateはないことは次のとおりです。最初の繰り返しで

  • それは(ループの前に宣言されたOrderDetailsエンティティが保存されます
  • それ以外の反復では、それは同じ既存のエンティティを更新します(最初の反復で挿入されます)

個別のエンティティインスタンスを個別のデータベースレコードとして保持する必要がある場合は、エンティティインスタンスを別にする必要があります。

+0

うわー、私はどのような違いがあるのか​​分かりませんが、うまくいきました。 :) –

+0

私は私の答えを編集しました、それは件名にいくつかの光を入れて欲しい:) –

+0

それはすべての今はもう一度、ありがとうございました:) –

関連する問題