2010-04-14 87 views
0

新的EJB3,請幫助/解釋。無法創建EntityManager

裏面一個會話bean我宣佈一個EntityManager如下

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

和工作原理。但是,當我做到這一點

private EntityManager em; 
private EntityManagerFactory emf; 

public void myFunction() { 
    emf = Persistence.createEntityManagerFactory("ScheduleUnit"); 
    em = emf.createEntityManager(); 
} 

我得到以下錯誤:

A JDBC Driver or DataSource class name must be specified in the ConnectionDriverName property 

回答

0

我認爲,EntityManagerFactory無法找到您的持久性單元中指定的數據源。至於Glassfish,此信息存儲在sun-resources.xml文件中。 它是j2ee應用程序嗎?如果是這樣,最好使用依賴注入與@PersistenceContext註釋(如帕斯卡爾說)。

此外,您還可以嘗試使用方法createEntityManagerFactory(String persistenceUnitName, Map properties)屬性指定「ConnectionDriverName」歡迎使用屬性地圖:

private EntityManager em; 
private EntityManagerFactory emf; 

public void myFunction() { 
    HashMap<String, String> properties = new HashMap<String, String>(); 
    properties.put("ConnectionDriverName", "org.postgresql.Driver"); //as for Postgres 
    emf = Persistence.createEntityManagerFactory("ScheduleUnit", properties); 
    em = emf.createEntityManager(); 
} 
+0

請參閱本文,如果您編寫j2se應用程序:http://java.sun.com/developer/technicalArticles/J2SE/Desktop/persistenceapi/ – Dmitry 2010-04-15 12:53:36

+0

感謝德米特里, 我使用Genonimo而不是Glassfish的J2EE服務器。我已經正確設置了數據源。
這是我的persistence.xml: org.apache.openjpa.persistence.PersistenceProviderImpl myDatasource com.skomarcorp.Schedule。你能解釋使用@PersistenceContext和EntityManagerFactory之間的區別,以及爲什麼一個比另一個更好? – duvo 2010-04-16 18:21:27

+0

使用註釋使代碼更簡單:)在這種情況下,容器(geronimo)會自動解析到實體管理器的鏈接,並且EntityManager實例的生命週期由容器管理。請參閱http://java.sun.com/javaee/5/docs/tutorial/doc/bnbqw.html – Dmitry 2010-04-20 18:27:08

0

,你使用第二代碼片段(它是在一個EJB如果是,你不應該還不清楚在託管環境(如EJB容器)中使用EntityManagerFactory)。你能澄清嗎?

也請顯示您的persistence.xml(錯誤信息是關於此文件不包含所需信息)。

+0

感謝回答帕斯卡。 是的,它在EJB中。對於我的應用程序,每個客戶端都有自己的數據庫,但業務邏輯對所有用戶來說都是一樣的,我想我可以爲每個客戶端創建一個持久性單元(PU),並在運行時選擇相應的PU。 這是我的persistence.xml: <持久性單元名稱= 「ScheduleUnit」 交易類型= 「JTA」> org.apache.openjpa.persistence.PersistenceProviderImpl myDatasource com.skomarcorp.Schedule duvo 2010-04-16 18:13:29