Home
Java Persistence API (JPA)
The Java Persistence API (JPA) provides an object-relational mapping facility for managing relational data in Java applications. Entity beans as specified in the EJB | .x specification have been replaced by JPA entity classes. These classes are annotated with the @Entity annotation. Entities can either use persistent fields (mapping annotation is applied to entity's instance variable) or persistent properties (mapping annotation is applied to getter methods for JavaBeans-style properties. All fields of a entity not annotated with the @Transient annotation or not marked with the transient Java keyword will be persisted to the data store. The object-relational mapping annotation must be applied to the instance variables. The primary key field is simply annotated with the @Id annotation.
There are four types of multiplicities in entity relationships:
One-to-one (@OneToOne): Each entity instance is related to a single instance of another entity.
One-to-many (@OneToMany): An entity instance can be related to multiple instances of the other entities.
Many-to-one (@ManyToOne): Multiple instances of entity can be related to a single instance of another entity.
Many-to-many (@ManyToMany): The entity instances can be related to multiple instances of each other. Entities are managed by the entity manager. The entity manager is an instance of javax.persistence.EntityManager and is associated with persistence context. A persistence context defines the scope under which particular entity instances are created, persisted, and removed. The EntityManager API creates and removes persistent entity instances, finds entities by its primary key, and allows queries to be run on entities. There are two kinds of entity managers available:
Container-managed entity manager: The persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction Architecture (JTA) transaction. To obtain an EntityManager instance, inject the entity manager into the application component: EntityManager em;
Application-managed entity manager: This is used when applications need to access a persistence context that is not propagated with the JTA transaction across EntityManager instances in a particular persistence unit. In this case, each EntityManager creates a new, isolated persistence context. To obtain an EntityManager instance, inject an EntityManagerFactory into the application component by means of the @PersistenceUnit annotation: EntityManagerFactory emf;
Then, obtain an EntityManager from the EntityManagerFactory instance:
EntityManager em = emf.createEntityManager();
ibm.com/redbooks