Java Reference
In-Depth Information
ItemManager
bean in the most obvious way possible—to update the database with an
existing
Item
:
public Item updateItem(Item item) {
entityManager.merge(item);
return item;
}
As soon as the
updateItem
method returns, the database is updated with the data from
the
Item
entity. The
merge
method must only be used for an entity that exists in the data-
base. An attempt to merge a nonexistent entity will result in an
IllegalArgumentEx-
ception
. The same is true if the
EntityManager
detects that the entity you're trying
to merge has already been deleted through the
remove
method, even if the
DELETE
state-
ment hasn't been issued yet.
Merging relationships
By default, entities associated with the entity being merged aren't merged as well. For
example, the
Seller
,
Bid
, and
Category
entities related to the
Item
aren't merged
when the
Item
is merged in the previous code snippet. But this behavior can be controlled
using the
cascade
element of the
@OneToOne
,
@OneToMany
,
@ManyToOne
, and
@ManyToMany
annotations. The
cascade
element is added to the annotation on the
owning side of the relationship. If the
cascade
element is set to either
ALL
or
MERGE
,
the related entities are merged. For example, the following code will cause the
Seller
entity related to the
Item
to be merged because the
cascade
element is set to
MERGE
:
public class Item {
@ManyToOne(cascade=CascadeType.MERGE)
public Seller getSeller() {
Note that as in most of the
EntityManager
's methods, the
merge
method must be
called from a transactional context or it'll throw a
TransactionRequiredExcep-
tion
. We'll now move on to the final element of the CRUD sequence: deleting an entity.
Detached entities and the DTO anti-pattern
If you've spent even a moderate amount of time using EJB 2, you're probably thoroughly
familiar with the data transfer object (DTO) anti-pattern. In a sense, the DTO anti-pattern