In addition to persisting and retrieving entities from the database, JPA also allows us to delete and update data from the database. Deleting is achieved using the remove()
method on the entity manager.
If we already have an instance on an entity that we wish to delete, we can simply call the remove()
method to delete it.
@PersistenceContext EntityManager em … em.remove(customer);
If we do not have an instance of an entity to remove, we can first find and load it from the database using the find()
method of the entity manager.
Customer customer = em.find(Customer.class, customerId); em.remove(customer);
To update an entity in the database, we simply get an instance of the object and invoke the relevant setters on it. As the code that is running is inside a Session Bean method using Container Managed Persistence, any changes to the object will be persisted to the database when the method exits. Once again, we can use the find()
method of the entity manager...