SCBCD Notes: Java Persistence (Part 1)
Published November 29th, 2006 in Java.The javax.persistence.EntityManager is the central service for all persistence actions. Entity beans are plain Java objects that interact with EntityManager to make them persistent. EntityManager has the following role:
- manages the object-relational mapping between a fixed set of entity classes and the underlying data source.
- provides APIs for creating queries, finding objects, synchronizing objects and inserting objects into the database.
- provides caching and manage the interaction between an entity and transactional services.
- tracks state changes to the entity bean.
EntityManager manages persistence context, a set of entity bean instances. When the persistence context is closed, all managed entity objects become detached and are unmanaged.
There are two types of persistence contexts: transaction-scoped and extended persistence context. If a persistence context lives as long as a transaction and be closed when the transaction completes, this is called transaction-scoped persistence context (only possible if managed by EJB container). Otherwise the persistence context exists across multiple transactions, this is called extended persistence context.
One interesting fact about detached entities in EJB 3.0 is that they can be serialized and sent across the network to a remote client. This eliminates the need of Value Object Pattern (Data Transfer Objects) often used in EJB 2.1 to achieve the same purpose.

A persistence unit is the fixed set of classes that EntityManager maps to the database. A persistence unit is defined in persistence.xml file in the META-INF directory. You can specify the set of classes or the persistence provider will scan and include every class that has @javax.persistence.Entity annotation. The rules of inclusion are as follow:
- Classes annotated with
@Entityin the persistence.xml file’s JAR file (unless<exclude-unlisted-classes>is specified) - Classes annotated with
@Entitythat are contained within any JARs listed with<jar-file>elements - Classes mapped in the
META-INF/orm.xmlfile if exists - Classes mapped in any XML files referenced with
<mapping-file>element - Classes listed with any
<class>elements


1 Response to “SCBCD Notes: Java Persistence (Part 1)”
Please Wait
Leave a Reply