2. Java Persistence API (JPA)
The Java Persistence API provides an object/relational mapping facility
to Java developers for managing relational data in Java applications.
Provided by the javax.persistence package
Part of EJB 3.0 specification (JSR 220)
Enables persisting POJO to relational database
Java Persistence consists of three areas:
• The Java Persistence API
• Object/relational mapping metadata (using annotations or in XML
deployment descriptor)
• The query language
3. Entity
An entity is a lightweight persistence domain object.
Typically, represents a table in a relational database
An entity class must follow these requirements:
annotated with the javax.persistence.Entity annotation.
have a public or protected, no-argument constructor.
not be declared final, including methods or persistent instance variables
If an entity instance be passed by value as a detached object, such as through a
session bean’s remote business interface, the class must implement the Serializable
interface.
may extend both entity and non-entity classes.
persistent instance variables must be declared private, protected, or package-private,
and can only be accessed directly by the entity class’s methods (get/set)
5. Persistence Context & Entity Manager
Persistence context
a set of managed entity instances that exist in a particular data store.
The EntityManager interface
defines the methods that are used to interact with the persistence context
creates and removes persistent entity instances
finds entities by the entity’s primary key
allows queries to be run on entities
6. Entity Manager
Container-Managed Entity Managers
an EntityManager instance’s persistence context is automatically propagated by the container to all
application components instance within a single Java Transaction Architecture (JTA) transaction.
Usually used in Java EE environment
@PersistenceContext
EntityManager em;
Application-Managed Entity Managers
the persistence context is not propagated to application components, and the life cycle
of EntityManager instances is managed by the application.
Usually used in Java SE environment
@PersistenceUnit
EntityManagerFactory emf;
EntityManager em = emf.createEntityManager();
8. XML Configuration files
persistance.xml
Defines the database and entity manager options for deploying JPA
applications
Packaged in the META-INF directory of the project
orm.xml
Stores metadata to describe object-relational mappings
Not really required – JPA spec emphasizes using annotation
Mapping on this file overrides any mapping defined using annotations