Transcript of "Introduction to JPA (JPA version 2.0)"
JPA version 2.0 Tutorial email@example.comDec 2011
Java Persistence API (JPA)The Java Persistence API provides an object/relational mapping facilityto 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 databaseJava Persistence consists of three areas:• The Java Persistence API• Object/relational mapping metadata (using annotations or in XML deployment descriptor)• The query language
EntityAn entity is a lightweight persistence domain object.Typically, represents a table in a relational databaseAn 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)
Persistence Context & Entity ManagerPersistence 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
Entity ManagerContainer-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();
XML Configuration filespersistance.xml Defines the database and entity manager options for deploying JPA applications Packaged in the META-INF directory of the projectorm.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