On Dec 18, 2009, at 9:04 AM, Mansour Al Akeel wrote:
On Thu, Dec 17, 2009 at 6:37 AM, David Blevins
<[email protected]> wrote:
On Dec 17, 2009, at 3:52 AM, Mansour Al Akeel wrote:
This should be fine depending on how you get your entity manager
reference
and how your persistence unit is declared. Your persistence unit
should be
of type TRANSACTION and you should be using @PersistenceContext to
get a
reference to the EntityManager (not @PersistenceUnit or an
EntityManagerFactory).
I don't understand, why would I keep the type TRANSACTION ? I have
RESOURCE_LOCAL since I want to handle everything from the bean ? From
the document you sent me states:
--------------------------
With <persistence-unit transaction-type="RESOURCE_LOCAL"> you are
responsible for EntityManager (PersistenceContext/Cache) creating and
tracking...
* You must use the EntityManagerFactory to get an EntityManager
* The resulting EntityManager instance is a PersistenceContext/
Cache
* An EntityManagerFactory can be injected via the @PersistenceUnit
annotation only (not @PersistenceContext)
--------------------------
Am I missing something ?
Maybe I can add some bullets to that doc.
The long and short of it is that if you are using a transaction
manager (either directly via UserTransaction or indirectly via
@TransactionAttribute) and you want the EntityManager (and related
DataSources) to cooperate with that transaction, then you need
TRANSACTION as your transaction-type.
Here's an commented version of the code you posted to clarify:
public Restaurant create(Restaurant obj)
{
try
{
Context ctx = new InitialContext();
UserTransaction ut = (UserTransaction) ctx
.lookup("java:comp/UserTransaction");
// request the transaction manager to start a
transaction
ut.begin();
// this line will cause an EntityManager to be
created under the covers
// and associated with the JTA transaction in
progress.
obj = getEntityManager().merge(obj);
getEntityManager().persist(obj);
// this line is not needed
getEntityManager().flush();
// this line will cause the transaction to end
// and the entitymanager to be flushed and closed
and discarded
ut.commit();
} catch (Exception e)
{
e.printStackTrace();
}
return obj;
}
You likely have things working already, but wanted to give some
explanation.
Hope that's clearer.
-David