People, Im studying for the new EJB3 certification. I would like the share some study notes with you guys. This is my BASIC notes about INTRODUCTION to Java Persistence API (I'll increase the complexity in the future). Please, improve and give suggestions =]. Im based on the Enterprise Java Beans 3.0 5th edition book (O'Reilly). Sorry for any English inconvenience, my native language is Portuguese =))).
---- -***ENTITY MANAGER*** (javax.persistence.EntityManager) is the central service for all persistence actions. -ENTITIES are pojos. They don't become persistent until interacts with the EntityManager to make them persistent. -EntityManager provides... --O/R mapping. --API to create queries, finding, synchronizing and inserting objects. --Caching. --Interaction with JTA. -EntityManager isn't limited to JEE environment (can use it in JSE). -States: Entity Managed (attached to an Entity Manager) vs. Unmanaged (detached from an Entity Manager).
-***PERSISTENCE CONTEXT*** is a set of managed entity object instances. -The Persistence Context are managed by an Entity Manager. -When a persistence context is close, all the managed entities become detached and are no longer managed (any state change will not be synchronized with the database). -There are Two types of Persistence Context: Transaction-Scoped and Extended Persistence Context. (1) In the Transaction-Scoped type, Persistence Context live as long a transaction and be closed when a transaction completes (the transaction Persistence Context will be destroyed and all managed entity become detached). -Only app server managed persistence contexts can be transaction-scoped (only EntityManager instances injected with the @PersistenceContext annotation or XML equivalent may be transaction-scoped). (2) Extended Persistence Context live longer than a transaction. The entity instances remain managed after a transaction is completed.
-***PERSISTENCE UNIT*** An EntityManager maps a fixed set of classes to a particular DB. This set of classes is called a Persistence Unit. -One or more Persistence Units are defined in a persistence.xml file (in the META-INF directory). -The set of classes in the Persistence Unit can be specified or the provider can scan the jar automatically (default) to determine the set of classes to deploy as entities. -When automatic mode is used, the provider look for the @javax.persistence.Entity annotation. -IMPORTANT NOTE: Each persistence unit is tied to one and only one data source. -persistence.xml exemple <persistence> <persistence-unit name="titan"> <!-- used by injection annotations --> <jta-data-source>java:/OracleDS</jta-data-source> <properties> <property name="org.hibernate.hbm2dll">update</property> </properties> </persistence-unit> </persistence>
-Obtaining an EntityManager in JAVA SE: -In Java SE EntityManagers are created by javax.persistence.EntityManagerFactory (Using the factory is possible but isn't a requirement in Java EE). -when finish to use the EntityManagerFactory you should close() (unless it is injected, when this occurs automatically) -javax.persistence.Persistence class is responsible for creating an EntityManagerFactory. EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnitName"); ... factory.close(); // <-- you should do that when using Java SE.
-Obtaining a Persistence Context -A Persistence Context can be created calling the EntityManagerFactory.createEntityManager() method. -createEntityManager() return an extended persistence context. -If EntityManagerFactory is JTA-enablea you must call the EntityManager.joinTransaction() method*. *If you are using EJB container managed persistence contexts, then you do not need to perform this. -An EntityManager can be injected directly into an EJB using the @javax.persistence.PersistenceContext annotation**. @PersistenceContext(unitName="persistenceUnitName",type=PersistenceContextType.EXTENDED) private EntityManager entityManager;*** ** the Transaction-Scoped Type is the default value. *** extended type is only allowed in Stateful Session Beans. When the stateful bean is removed, the persistence context is closed. -It is strongly suggested that you use the @PersistenceContext or the XML equivalent instead of EntityManagerFactory when you using Java Persistence with EJBs.
===API=== entityManager.persist(entityobject); -> Queue for insertion and the object becomes managed. Throw an IllegalArgumentException if entityobject is not an entity type. entityManager.flush(); -> Force manually insertion. entityManager.find(entityClass, primaryKey); -> Find by PK. If not found, null is returned. Customer c = entityManager.find(Customer.class,2); entityManager.getReference(entityClass, primaryKey); -> Get Reference by PK. If not found, throw an EntityNotFoundException. entityManager.createQuery(); Query query = entityManager.createQuery("from Customer c where id=2"); Custumer cust = (Custumer)query.getSingleResult(); note: All query, find or getReference are managed by the Persistence Context, and they return the same entity instance. entityManager.merge(entityobject); -> Attach the entity object to the Persistence Context. Cabin entityCopy = entityManager.merge(entityObjectParam);* *entityCopy is managed by the entity manager, entityObjectParam still detached. entityManager.remove(entityObject); Throw TransactionRequiredException if this method is invoked on a transaction-scoped persistence context. -> Queue for delete. Throw TransactionRequiredException if this method is invoked on a transaction-scoped persistence context. entityManager.refresh(entityObject); -> Refreshes the state of the entity from database, overwriting any changes made to that object. Throw TransactionRequiredException if this method is invoked on a transaction-scoped persistence context. Throw EntityNotFoundException if another thread removed the object. entityManager.contains(entityObject); -> Return true if the entityObject instance is currently being managed by the persistence context. entityManager.clear() -> Detach all managed entity instances from a persistence context. Any changes you have made will be lost. -> Use flush() before clear() to avoid data lost.
entityManager.setFlushMode(FlushModeType.AUTO | FlushModeType.COMMIT); .When you call persist(), merge() or remove(), these changes ARE NOT synchronized with de database until the EntityManager decide to flush. .You can force the synch using flush(). By default flush happens before a correlated query is executed or transaction commit time (AUTO mode). .When COMMIT mode is on, the flush ocurrs only when the transaction commits.
Resource Local Transactions. -EntityManagers persistence context is usually JTA default in a Java EE environment. EntityTransaction.begin(); .commit(); .rollback(); isActive(); -In a non-Java EE environment, JTA is not avaliable, so JPA provide the EntityTransaction interface to local control of transactions. -You cannot use EntityTransactions if the transaction type of your persistence unit is JTA.