3.5. Modifying persistent objects
Transactional managed instances (ie. objects loaded, saved, created or queried by the entity manager) may be manipulated by the application and any changes to persistent state will be persisted when the Entity manager is flushed (discussed later in this chapter). There is no need to call a particular method to make your modifications persistent. A straightforward way to update the state of an entity instance is to
find()
it, and then manipulate it directly, while the persistence context is open:
Cat cat = em.find( Cat.class, new Long(69) ); cat.setName("PK"); em.flush(); // changes to cat are automatically detected and persisted
Sometimes this programming model is inefficient since it would require both an SQL SELECT (to load an object) and an SQL UPDATE (to persist its updated state) in the same session. Therefore Hibernate offers an alternate approach, using detached instances.