Fork me on GitHub

Programming Design Notes

將 Seam 的 Hibernate Persistence Provider 轉為 EclipseLink

| Comments

JBoss Seam Framework 預設的 Persistence ProviderHibernate,但 Hibernate 未必能夠滿足不同 Database 的需求,Seam 亦提供了一種方法將 Hibernate 轉為 OpenJPA 或其他 Persistence Provider

如果你需要將 Hibernate 轉為使用 OpenJPA 可參考這篇: http://seamframework.org/Documentation/UsingOpenJPAAsPersistenceProviderInsteadOfHibernate

以下的是將 Hibernate 轉為使用 EclipseLink 的方法。

首先要更改 persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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_1_0.xsd"
version="1.0">
<persistence-unit name="ctlok" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<non-jta-data-source>jdbc/oracle</non-jta-data-source>
<class>com.ctlok.pro.entity.User</class>
<class>com.ctlok.pro.entity.UserInfo</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.target-server" value="Websphere" />
<property name="eclipselink.target-database" value="Oracle" />
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.logging.timestamp" value="true" />
<property name="eclipselink.logging.session" value="true" />
<property name="eclipselink.logging.thread" value="false" />
<property name="eclipselink.logging.exceptions" value="true" />
<property name="eclipselink.cache.type.default" value="NONE" />
</properties>
</persistence-unit>
</persistence>

properties 的設定請自行更改。

重要的是:
  • transaction-type 一定要是 RESOURCE_LOCAL
  • provider 改成是 EclipseLinkPersistenceProvider
  • 一定要是 non-jta-data-source
  • 將所有 Entity Class 也加到 persistence.xml

設定好 persistence.xml 後,要設定 components.xml:

components.xml 加入以下的設定:
<transaction:entity-transaction
entity-manager="#{entityManager}" />

<persistence:entity-manager-factory
persistence-unit-name="ctlok" name="entityManagerFactory" startup="false" />

<persistence:managed-persistence-context
name="entityManager" auto-create="true" entity-manager-factory="#{entityManagerFactory}" />

<component class="org.jboss.seam.persistence.PersistenceProvider"
name="org.jboss.seam.persistence.persistenceProvider" scope="stateless" />

請記得要更改 persistence-unit-namepersistence.xml 所設定的名稱。

這樣就可以將 Hibernate 轉為使用 EclipseLink 了。

相關書籍: JBoss(R) Seam: Simplicity and Power Beyond Java(TM) EEBeginning JSF&trade; 2 APIs and JBoss® Seam (Expert's Voice in Java)Beginning JSF&trade; 2 APIs and JBoss® Seam