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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Dragos
  • 2,911
  • 12
  • 39
  • 55
  • Have you read this link: http://docs.oracle.com/cd/B32110_01/web.1013/b28221/usclient003.htm – melihcelik Jan 05 '12 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 Jan 05 '12 at 11:52
  • @Perception I am not using EJBs so I do not know how to make those injections. Please advise... – Dragos Jan 05 '12 at 12:33

1 Answers1

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.

Community
  • 1
  • 1
Andre
  • 691
  • 3
  • 11