stackoverflow
stackoverflow

Reputation: 19474

Do you need to createEntityManager() everytime you are accessing your db?

If you are exercising CRUD procedures do you have to do this (with transaction type: RESOURCE_LOCAL not JTA)

@PersistenceUnit(unitName="mongo")
EntityManagerFactory emf;

EntityManager em;


@Inject
private SomeObj injectableObj;

public void create()
{
   em = emf.createEntityManager(); <---- here
   SomeObj obj = new SomeObj();
   em.persist(obj);
}

public void read()
{
   em = emf.createEntityManager();  <---- here
   Query query = em.createQuery("Select s from SomeObj s");

}

public void update()
{
   em = emf.createEntityManager();  <---- here
   SomeObj s = em.find(SomeObj.class, injectableObj.getId());
   s.setSomeObj(injectableObj.getSomeObj());

}

public void delete()
{

   em = emf.createEntityManager();  <---- here
   SomeObj s = em.find(SomeObj.class, injectableObj.getId());
   em.remove(s);
}

Question: Is there anyway to inject the EntityManager?

Upvotes: 1

Views: 1719

Answers (2)

gkuzmin
gkuzmin

Reputation: 2474

You can use injection. I use it like this:

@PersistenceContext(unitName = "some_jndi_name")
private EntityManager em;

Upvotes: 0

kinaesthesia
kinaesthesia

Reputation: 703

Maybe try to look here for exemples :

Injections EntityManager

I prefer to use : Injection via @PersistenceContext

Upvotes: 1

Related Questions