1

I am new to JPA 2 and I want to find out which are the best practices for handling an EntityManager on RESOURCE_LOCAL and with JTA. From what I have read, I should be able to make a dependency injection, but I do not quite understand how.

I am using EclipseLink as an implementation.

3
  • Have you read this link: docs.oracle.com/cd/B32110_01/web.1013/b28221/usclient003.htm
    – melihcelik
    Commented Jan 5, 2012 at 11:01
  • What problem are you having exactly? You can inject an EntityManager directly into your code but there are a few gotcha's you have to watch out for. Please edit your question to include the specific error or problem.
    – Perception
    Commented Jan 5, 2012 at 11:52
  • @Perception I am not using EJBs so I do not know how to make those injections. Please advise...
    – Dragos
    Commented Jan 5, 2012 at 12:33

1 Answer 1

2

To obtain a reference to EntityManager in your bean, use the following annotation:

@PersistenceContext
private EntityManager entityManager;

Or if you are not using EJB:

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myPersistenceUnitName");
EntityManager entityManager = entityManagerFactory.createEntityManager();
//Do some work...
entityManager.close();
entityManagerFactory.close();

See Persistence unit as RESOURCE_LOCAL or JTA? for an explanation of RESOURCE_LOCAL vs JTA.

2
  • I am not using EJBs. Where and how does the application find the right EntityManager?
    – Dragos
    Commented Jan 5, 2012 at 12:30
  • Then you have to use javax.persistence.EntityManagerFactory (answer edited)
    – Andre
    Commented Jan 5, 2012 at 12:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.