Java Reference
In-Depth Information
An entity retrieved from the database using the EntityManager 's find method or one
of the query methods is attached if retrieved within a transactional context. A retrieved in-
stance of the entity becomes detached immediately if there's no associated transaction.
If you have a detached entity, you have two methods to reattach it. The first is by using the
merge method. The merge method accepts a detached entity as a parameter and returns
an attached entity. The merge method will use the detached entity parameter to find the
database data again and create a new attached entity. It'll then copy any changes from the
detached entity parameter into the new attached entity. The method then returns the new
attached entity. Before the transaction is ended, any changes to this new attached entity are
persisted to the database; therefore, the database gets updated with the new values from the
detached entity parameter.
The second method is find . Use the primary key of your detached entity to query the data-
base and return a new attached entity. Because we're talking about detached entities, we'll
cover them in more detail next.
Detached entities
A detached entity is an entity that's no longer managed by the EntityManager and
there's no guarantee that the state of the entity is in synch with the database. Detachment
and merge operations become handy when you want to pass an entity across application
tiers. For example, you can detach an entity and pass it to the web tier, then update it and
send it back to the EJB tier, where you can merge the detached entity to the persistence
context.
The usual way entities become detached is a little subtler. Essentially, an attached entity
becomes detached as soon as it goes out of the EntityManager context's scope. Think
of this as the expiration of the invisible link between an entity and the EntityManager
at the end of a logical unit of work or a session. An EntityManager session could be
limited to a single method call or span an arbitrary length of time. (Reminds you of session
beans, doesn't it? As you'll soon see, this isn't entirely an accident.) For an EntityMan-
ager whose session is limited to a method call, all entities attached to it become detached
as soon as a method returns, even if the entity objects are used outside the method. If this
isn't crystal clear right now, it will be once we talk about the EntityManager 's persist-
ence context in the next section.
Search WWH ::




Custom Search