Entity manager tutorial: Updating entries
If you want to change an entity, you can find the instance, update the instance and any referenced entities, and commit the transaction.
Before you begin
Procedure
Update entries.
The following example demonstrates how to find the Order
instance, change it and any referenced entities, and commit the transaction.
public static void updateCustomerOrder(EntityManager em) {
em.getTransaction().begin();
Order order = (Order) em.find(Order.class, "ORDER_1");
processDiscount(order, 10);
Customer cust = order.customer;
cust.phoneNumber = "5075551234";
em.getTransaction().commit();
}
public static void processDiscount(Order order, double discountPct) {
for(OrderLine line : order.lines) {
line.price = line.price * ((100-discountPct)/100);
}
}
Flushing the transaction synchronizes all managed entities with
the cache. When a transaction is committed, a flush automatically occurs. In this case, the Order
becomes a managed entity. Any entities that are referenced from the Order, Customer, and OrderLine
also become managed entities. When the transaction is flushed, each of the entities are checked to
determine if they have been modified. Those that are modified are updated in the cache. After the
transaction completes, by either being committed or rolled back, the entities become detached and
any changes that are made in the entities are not reflected in the cache.