[英]Issue Wiring an EntityManager from EntityManagerFactory
[英]create EntityManager from EntityManagerFactory
我正在嘗試在servlet中獲取jpa EntityManager
的實例,如下所示
ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
EntityManagerFactory emf = (EntityManagerFactory)context.getBean("entityManagerFactory");
EntityManager em=emf.createEntityManager();
我的問題是,這是在servlet get服務方法中獲取EntityManager實例的有效方法。 同樣,我們應該在上述方法中顯式關閉EntityManagerFactory
/ EntityManager
。
由於您使用的是彈簧,因此理想情況下,您應該使用另一層(例如DAO)
@PersistenceContext
private EntityManager entityManager;
春天會解決這個問題。
如果您確實需要在servlet中而不是在spring-mvc @Controller
,則可以從應用程序上下文中獲取service / dao bean,並在那里使用上述構造。 並且,如果出於某些奇怪的原因,您應該手動處理實體管理器-是的,則必須對其進行.close()
處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.