In the persistence.xml JPA configuration file, you can have a line like:
<persistence-unit name="com.nz_war_1.0-SNAPSHOTPU" transaction-type="JTA">
or sometimes:
<persistence-unit name="com.nz_war_1.0-SNAPSHOTPU" transaction-type=”RESOURCE_LOCAL”>
My question is:
What is the difference between transaction-type="JTA"
and transaction-type=”RESOURCE_LOCAL”
?
I also noticed some persistence.xml files with the transaction-type missing. Is it correct?
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
EntityManagerFactory
to get anEntityManager
- The resulting
EntityManager
instance is aPersistenceContext/Cache
AnEntityManagerFactory
can be injected via the@PersistenceUnit
annotation only (not@PersistenceContext
) - You are not allowed to use
@PersistenceContext
to refer to a unit of typeRESOURCE_LOCAL
- You must use the
EntityTransaction
API to begin/commit around every call to yourEntityManger
- Calling
entityManagerFactory.createEntityManager()
twice results in two separateEntityManager
instances and therefor two separatePersistenceContexts/Caches
. - It is almost never a good idea to have more than one instance of an
EntityManager
in 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
EntityManagerFactory
to get anEntityManager
- You can only get an
EntityManager
supplied by the container - An
EntityManager
can be injected via the@PersistenceContext
annotation only (not@PersistenceUnit
) - You are not allowed to use
@PersistenceUnit
to refer to a unit of type JTA - The
EntityManager
given by the container is a reference to thePersistenceContext/Cache
associated with a JTA Transaction. - If no JTA transaction is in progress, the
EntityManager
cannot be used because there is noPersistenceContext/Cache
. - Everyone with an
EntityManager
reference to the same unit in the same transaction will automatically have a reference to the samePersistenceContext/Cache
- The
PersistenceContext/Cache
is flushed and cleared at JTA commit time
来源:https://stackoverflow.com/questions/17331024/persistence-xml-different-transaction-type-attributes