jsr338-experts@jpa-spec.java.net

[jsr338-experts] Re: EntityManager access in the entities

From: Gordon Yorke <gordon.yorke_at_oracle.com>
Date: Tue, 21 Jun 2011 15:54:35 -0300

This seems far to limiting to be useful and requires that some component
of the application is referencing the EM anyway as these Entities need
to be "attached" to an EM for the EM to be available. If the intended
use case is to have the EM injected on read and then the EM is "thrown
away" by the application you run the very real risk of having the EM
closed by garbage collection as any provider that did not want to run
the risk of a customer induced memory leak would actually be injecting a
proxy with a weak reference.

The issue does not seem to be about the richness of the domain model but
rather a missing mechanism to managed the EntityManager for the
application. It's not clear to me why your existing solution requires a
ThreadLocal EM. If you are querying Read Committed data then you can
simply use a cached EM or create a new one for each query. If you need
the EM associated with the current transaction then the transaction
management artifact can manage the EM and provide it to the rich domain
model.

Is this just an issue in search of a better pattern? Would more active
management of the Application Managed PeristenceContext through the
Persistence.class API provide the needed functionality? Can you provide
an example of the EM management code you are creating each time and the
application flow for this usecase?

--Gordon

Adam Bien wrote:
> Hi All,
>
> I would like to introduce a LifecycleListener and Lifecycle Call Back methods like:
>
>
> @PostAttach
> public void postAttach(EntityManager manager){
>
> }
>
> @PreDetach
> public void preDetach(){}
>
> Reason:
>
> In rich domain entities it is often required to get a reference to an EntityManager to be able to create and persist new entities or to perform queries.
>
> Currently it is only possible with workarounds like using ThreadLocal or ThreadSynchronizationRegistry. With an extension of the lifecycle listener you would get
> a reference to an EntityManager and will get notified in case it is no more valid.
>
> Injection of the EntityManager would be the best/easiest solution, however JPA-entities are managed by the EntityManager and not by the container...
>
> I have the issue in every non-trivial project with a rich domain object model. There are, however, no issues with an anemic (http://www.martinfowler.com/bliki/AnemicDomainModel.html) model, because usually the EJBs / CDI managed beans do implement the business logic.
>
> see also: http://www.adam-bien.com/roller/abien/entry/why_sometimes_the_entitymanager_in
>
> best regards,
>
> adam
>
>