adam bien's blog

How To Treat The JPA EntityManager? 📎

The structure of the JPA EntityManager is surprisingly similar to the Domain Store Pattern. Strictly speaking EntityManager is the realization of the Domain Store pattern.

The Domain Store pattern itself is an object oriented variation of the Data Access Object pattern. It could be even considered as "DAO 2.0". See also post DAO -- Reader's Questions.

Because the EntityManager already encapsulates the concrete ORM-implementation, as well as, the underlying database, there is no need for any further layer of indirection.

From the conceptual perspective the EntityManager is a generic, out-of-the-box Control. Therefore there is no need for any further wrapping and you can inject the EntityManager directly to the Boundary.

So, whats the difference between a regular Control and the EntityManager?

Methods of a typical Control are coarser, than EntityManager's methods. Naturally the interactions with EntityManager (particularly the construction of queries), can require a considerable amount of code. However this will result in a complex Boundary and lead to refactoring: the code of a bloated Boundary is going to be factored out anyway into Controls. At this place there is no difference between reducing the complexity of a Boundary caused by business code or caused by direct interaction with EntityManager and the construction of JPA QL queries. Simple CRUD operations still remain simple and do not require any refactoring.

J2EE design was based on top down principles, Java EE is rather "bottom up": you should refactor on demand and not upfront. Empty layers and wrappers were a best practice in the J2EE era, but are an anti-pattern now (Java EE 5/6/7/*).

[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 259 in chapter "Data Access Object", page 419 in chapter "Entity Control Boundary (ECB)—The Lean Way" and page 83 in chapter "Control"]

See you at Java EE Workshops at MUC Airport, particularly at the Java EE Architectures workshop!