如果您在行使CRUD方法做你必須做這個(交易類型:RESOURCE_LOCAL沒有JTA)你每次訪問你的數據庫時都需要創建EntityManager()嗎?
@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);
}
問:反正是有注入的EntityManager?
你需要使用ThreadLocal這種類型的任務。請看這裏http://www.naildrivin5.com/daveblog5000/?p=39和這裏http://javanotepad.blogspot.com/2007/08/managing-jpa-entitymanager-lifecycle.html - 這是給更多實現細節 – 2012-07-31 14:14:39