Java Reference
In-Depth Information
10.2.3. Updating entities
Recall that the EntityManager makes sure that changes made to attached entities are
always saved into the database behind the scenes. This means that for the most part, the
application doesn't need to worry about manually calling any methods to update the entity.
This is perhaps the most elegant feature of ORM-based persistence because this hides data
synchronization behind the scenes and truly allows entities to behave like POJOs. Take the
code in the next listing, which updates an item that's being auctioned. Often after an item
has been listed it's necessary to update its description or picture if the item fails to attract
attention.
Listing 10.7. Transparent management of attached entities
Other than looking up the item, little is done using the EntityManager in the up-
dateItem method. After each method is invoked, the EntityManager ensures that the
changes are persisted to the database. Typically, all changes are persisted when the transac-
tion ends and the EntityManager attempts to commit all the changes. But you can force
persistence at any time by using the EntityManager flush method. When flush is
called, it applies to all entities managed in the persistence context. Flushing is controlled
by the FlushModeType . FlushTypeMode.AUTO means to persist to the database at
query execution time. FlushTypeMode.COMMIT will persist to the database when the
transaction ends and is committed.
Detachment and merge operations
Although managed entities are extremely useful, the problem is that it's difficult to keep
entities attached at all times. Often the entities will need to be detached and serialized at
the web tier where the entity is changed, outside the scope of the EntityManager . In
addition, recall that stateless session beans can't guarantee that calls from the same client
Search WWH ::




Custom Search