File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes EJB Certification (SCBCD/OCPJBCD) and the fly likes EJB3 Beta Certification - EntityManager BASIC notes. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "EJB3 Beta Certification - EntityManager BASIC notes." Watch "EJB3 Beta Certification - EntityManager BASIC notes." New topic
Author

EJB3 Beta Certification - EntityManager BASIC notes.

Wanderlei C. A. Souza
Greenhorn

Joined: Dec 13, 2006
Posts: 5
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 an EntityManager in JAVA EE:
-@javax.persistence.PersistenceUnit annotation is used in Java EE environment.
@PersistenceUnit(unitName="persistenceUnitName") private EntityManagerFactory factory;
-if you call close() on an injected EntityManagerFactory, an IllegalStateException is thrown.

-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.


SCJA, SCJP 5
Shoaib Khanzada
Ranch Hand

Joined: Jan 24, 2004
Posts: 34
Thats nice!!!, thanks
amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 810
i am reading ejb3.0 by oreilly,

but not able to understand the following thing written above,

Obtaining an EntityManager in JAVA EE:
-@javax.persistence.PersistenceUnit annotation is used in Java EE environment.
@PersistenceUnit(unitName="persistenceUnitName") private EntityManagerFactory factory;
-if you call close() on an injected EntityManagerFactory, an IllegalStateException is thrown.

-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.


---------
i mean i am getting confused both above and in ejb book because some times somewhere in the book, somthing different is written ..mixing above text..

please remove my confusion.. would be great...
------------------------
apart from that
can anybody kindly explain me, if you are clear with funda writtein in page 73 to 75 in oreilly book of ejb 3,

i am not clear with the warning given on page 75, just above the heading "Interacting with an EntityManager"
also annotation material given page 72(bottom) and page 74(top)


best regards
amit


Thanks and Regards, Amit Taneja
Luiz Reginaldo Curado
Ranch Hand

Joined: Jan 19, 2006
Posts: 108
Good job, Wanderlei!

Thanks for your notes!
Wanderlei C. A. Souza
Greenhorn

Joined: Dec 13, 2006
Posts: 5
Amita,
In JEE/EJB3 enviroments (like JBoss) is better you use directly the @PersistenceContext annotation to obtain the PersistenceContext.

In JSE environment, you don't have the JEE facilities. In this situation, you need to create an EntityManagerFactory (using javax.persistence.Persistence) to get the PersistenceContext.

PersistenceContext is what really matters.

EntityManager manage the PersistenceContext and the PersistenceContext is in association with PersistenceUnit (described in persistence.xml file).

Thats it =)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: EJB3 Beta Certification - EntityManager BASIC notes.