69916 次
1 回答
120
Defaults
Default to JTA in a JavaEE environment and to RESOURCE_LOCAL in a JavaSE environment.
RESOURCE_LOCAL
With <persistence-unit transaction-type="RESOURCE_LOCAL"> you are responsible for EntityManager (PersistenceContext/Cache) creating and tracking
- You must use the
EntityManagerFactoryto get anEntityManager - The resulting
EntityManagerinstance is aPersistenceContext/CacheAnEntityManagerFactorycan be injected via the@PersistenceUnitannotation only (not@PersistenceContext) - You are not allowed to use
@PersistenceContextto refer to a unit of typeRESOURCE_LOCAL - You must use the
EntityTransactionAPI to begin/commit around every call to yourEntityManger - Calling
entityManagerFactory.createEntityManager()twice results in two separateEntityManagerinstances and therefor two separatePersistenceContexts/Caches. - It is almost never a good idea to have more than one instance of an
EntityManagerin use (don't create a second one unless you've destroyed the first)
JTA
With <persistence-unit transaction-type="JTA"> the container will do EntityManager (PersistenceContext/Cache) creating and tracking.
- You cannot use the
EntityManagerFactoryto get anEntityManager - You can only get an
EntityManagersupplied by the container - An
EntityManagercan be injected via the@PersistenceContextannotation only (not@PersistenceUnit) - You are not allowed to use
@PersistenceUnitto refer to a unit of type JTA - The
EntityManagergiven by the container is a reference to thePersistenceContext/Cacheassociated with a JTA Transaction. - If no JTA transaction is in progress, the
EntityManagercannot be used because there is noPersistenceContext/Cache. - Everyone with an
EntityManagerreference to the same unit in the same transaction will automatically have a reference to the samePersistenceContext/Cache - The
PersistenceContext/Cacheis flushed and cleared at JTA commit time
于 2013-06-26T22:59:45.403 回答