Hibernate - save multiple objects in one transaction
<p>I'm struggling to save multiple records to database with Hibernate. I don't open sessions or start transactions manually, and I'd love to avoid doing that if possible. My Service class looks like this:</p>

<pre><code>@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&lt;Integer, CartItem&gt; 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());
    }
...

}
</code></pre>

<p>Now, everytime I run save method, i'd like to save one record to database, however in current state it saves only the last item ( I guess it commits transaction only at the end) Sql output:</p>

<pre><code>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=?
</code></pre>

<p>My repository class doesn't do anything besides calling persist method.</p>

<p>Is it possible to save multiple records to database in Hibernate while using Transactional annotation? I'd like to keep this annotation in my service class.</p>