I've got a function that is supposed to loop through a list of OrderItems and update the quantity of each corresponding InventoryItem in the database, however its not working. There are no errors, but the inventory item quantities just aren't being updated.
public void completeOrder(Users user, Orders order)
{
List<OrderItem> orderItems = getOrderItems(user, order);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Assignment2PU");
EntityManager em = emf.createEntityManager();
for (OrderItem item : orderItems)
{
em.getTransaction().begin();
InventoryItem invItem = item.getInventoryItem();
System.out.println("decreasing " + invItem.getItemName() + ": " + invItem.getItemQty() + " by " + item.getQty());
int newQty = invItem.getItemQty() - item.getQty();
invItem.setItemQty(newQty);
em.getTransaction().commit();
}
}
The way I understand it, em.getTransaction().begin();
opens the transaction, I make some changes, then em.getTransaction().commit();
will persist those changes to the database. Is this incorrect?
It's missing the em.merge() to signal the entity manager that you want to persist the changes