在許多關於JPA的文檔中,我已經讀過告訴我需要一個Persistence文件來處理JPA。這個文件是在我創建JPA項目時自動創建的,但現在我想在RAP項目中使用JPA,並且也在RCP項目中使用JPA。但我不知道如何製作。如何在RCP或RAP項目中添加JPA Persistence.xml文件?
需要幫助。
在許多關於JPA的文檔中,我已經讀過告訴我需要一個Persistence文件來處理JPA。這個文件是在我創建JPA項目時自動創建的,但現在我想在RAP項目中使用JPA,並且也在RCP項目中使用JPA。但我不知道如何製作。如何在RCP或RAP項目中添加JPA Persistence.xml文件?
需要幫助。
只需在您的META-INF
文件夾中創建新的XML文件,即persistence.xml
。這個文件的內容應該是這樣的(請參考JPA文件中的具體問題的情況下):
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="pu" transaction-type="RESOURCE_LOCAL">
<class>DummyEntity</class>
<properties>
<property name="javax.persistence.jdbc.url" value="database-url" />
<property name="javax.persistence.jdbc.user" value="database-user" />
<property name="javax.persistence.jdbc.password" value="database-password" />
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
</properties>
</persistence-unit>
</persistence>
之後,您可以創建一個EntityManagerFactory
,使用下面的示例代碼:
import javax.persistence.EntityManagerFactory;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.jpa.osgi.PersistenceProvider;
Map<String, Object> connectionProperties = new HashMap<String, Object>();
connectionProperties.put(PersistenceUnitProperties.CLASSLOADER, this
.getClass().getClassLoader());
try {
EntityManagerFactory emf = new PersistenceProvider()
.createEntityManagerFactory("pu", connectionProperties);
} catch (Exception e) {
// todo
}
我發現一種方法是使用Project Facets
。
右鍵單擊您的項目 - >屬性 - > Project Facets - >檢查JPA
框。
這會自動在您的META-INF
文件夾中創建persistence.xml
文件。那麼你只需要建立一個連接來與JPA一起工作。
謝謝你的回答。我發現一個更簡單的方法是使用'Project Facets'。 – gamo 2014-09-03 08:06:50