JBoss Community Archive (Read Only)

JBoss AS 7.2

JPA Reference Guide

Introduction

The JBoss Application Server JPA subsystem implements the JPA 2.0 container-managed requirements. Deploys the persistence unit definitions, the persistence unit/context annotations and persistence unit/context references in the deployment descriptor. JPA Applications use the Hibernate (core) 4.0 persistence provider, that is included with JBoss AS. The JPA subsystem uses the standard SPI (javax.persistence.spi.PersistenceProvider) to access the Hibernate persistence provider and some additional extensions as well.

During application deployment, JPA use is detected (e.g. persistence.xml or @PersistenceContext/Unit annotations) and injects Hibernate dependencies into the application deployment. This makes it easy to deploy JPA applications.

In the remainder of this documentation, ”entity manager” refers to an instance of the javax.persistence.EntityManager class. Javadoc for the JPA interfaces http://download.oracle.com/javaee/6/api/javax/persistence/package-summary.html and JPA 2.0 specification. The index of Hibernate documentationis here.

Entity manager

The entity manager is similar to the Hibernate Session class; applications use it to create/read/update/delete data (and related operations). Applications can use application-managed or container-managed entity managers. Keep in mind that the entity manager is not expected to be thread safe (don't inject it into a servlet class variable which is visible to multiple threads).

Application-managed entity manager

Application-managed entity managers provide direct access to the underlying persistence provider (org.hibernate.ejb.HibernatePersistence). The scope of the application-managed entity manager is from when the application creates it and lasts until the app closes it. Use the @PersistenceUnit annotation to inject a persistence unit into a javax.persistence.EntityManagerFactory. The EntityManagerFactory can return an application-managed entity manager.

Container-managed entity manager

Container-managed entity managers auto-magically manage the underlying persistence provider for the application. Container-managed entity managers may use transaction-scoped persistence contexts or extended persistence contexts. The container-managed entity manager will create instances of the underlying persistence provider as needed. Every time that a new underlying persistence provider (org.hibernate.ejb.HibernatePersistence) instance is created, a new persistence context is also created (as an implementation detail of the underlying persistence provider).

Persistence Context

The JPA persistence context contains the entities managed by the persistence provider. The persistence context acts like a first level (transactional) cache for interacting with the datasource. Loaded entities are placed into the persistence context before being returned to the application. Entities changes are also placed into the persistence context (to be saved in the database when the transaction commits).

Transaction-scoped Persistence Context

The transaction-scoped persistence context coordinates with the (active) JTA transaction.  When the transaction commits, the persistence context is flushed to the datasource (entity objects are detached but may still be referenced by application code).  All entity changes that are expected to be saved to the datasource, must be made during a transaction.  Entities read outside of a transaction will be detached when the entity manager invocation completes.  Example transaction-scoped persistence context is below.

@Stateful  // will use container managed transactions
public class CustomerManager {
  @PersistenceContext(unitName = "customerPU") // default type is PersistenceContextType.TRANSACTION
  EntityManager em;
  public customer createCustomer(String name, String address) {
    Customer customer = new Customer(name, address);
    em.persist(customer);  // persist new Customer when JTA transaction completes (when method ends).
                           // internally:
                           //    1. Look for existing "customerPU" persistence context in active JTA transaction and use if found.
                           //    2. Else create new "customerPU" persistence context (e.g. instance of org.hibernate.ejb.HibernatePersistence)
                           //       and put in current active JTA transaction.
    return customer;       // return Customer entity (will be detached from the persistence context when caller gets control)
  }  // Transaction.commit will be called, Customer entity will be persisted to the database and "customerPU" persistence context closed

Extended Persistence Context

The (ee container managed) extended persistence context can span multiple transactions and allows data modifications to be queued up (like a shopping cart), without an active JTA transaction (to be applied during the next JTA TX). The Container-managed extended persistence context can only be injected into a stateful session bean. 

@PersistenceContext(type = PersistenceContextType.EXTENDED, unitName = "inventoryPU")
EntityManager em;

Extended Persistence Context Inheritance

JPA 2.0 specification section 7.6.2.1

If a stateful session bean instantiates a stateful session bean (executing in the same EJB container instance) which also has such an extended persistence context, the extended persistence context of the first stateful session bean is inherited by the second stateful session bean and bound to it, and this rule recursively applies—independently of whether transactions are active or not at the point of the creation of the stateful session beans.

By default, the current stateful session bean being created, will (deeply) inherit the extended persistence context from any stateful session bean executing in the current Java thread.  The deep inheritance of extended persistence context includes walking multiple levels up the stateful bean call stack (inheriting from parent beans).  The deep inheritance of extended persistence context includes sibling beans.  For example, parentA references child beans beanBwithXPC &  beanCwithXPC.  Even though parentA doesn't have an extended persistence context, beanBwithXPC & beanCwithXPC will share the same extended persistence context. 

Some other EE application servers, use shallow inheritance, where stateful session bean only inherit from the parent stateful session bean (if there is a parent bean).  Sibling beans do not share the same extended persistence context unless their (common) parent bean also has the same extended persistence context.

Applications can include a (top-level) jboss-all.xml deployment descriptor that specifies either the (default) DEEP extended persistence context inheritance or SHALLOW.

The AS/docs/schema/jboss-jpa_1_0.xsd describes the jboss-jpa deployment descriptor that may be included in the jboss-all.xml.  Below is an example of using SHALLOW extended persistence context inheritance:

<jboss>
    <jboss-jpa xmlns="http://www.jboss.com/xml/ns/javaee">
    <extended-persistence inheritance="SHALLOW"/>
    </jboss-jpa>
</jboss> 

Below is an example of using DEEP extended persistence inheritance:

<jboss>
    <jboss-jpa xmlns="http://www.jboss.com/xml/ns/javaee">
    <extended-persistence inheritance="DEEP"/>
    </jboss-jpa>
</jboss>

The AS console/cli can change the default extended persistence context setting (DEEP or SHALLOW).  The following cli commands will read the current JPA settings and enable SHALLOW extended persistence context inheritance for applications that do not include the jboss-jpa deployment descriptor:

./jboss-cli.sh
cd subsystem=jpa
:read-resource
:write-attribute(name=default-extended-persistence-inheritance,value="SHALLOW")

Entities

JPA 2.0 makes it easy to use your (pojo) plain old Java class to represent a database table row.

@PersistenceContext EntityManager em;
Integer bomPk = getIndexKeyValue();
BillOfMaterials bom = em.find(BillOfMaterials.class, bomPk); // read existing table row into BillOfMaterials class

BillOfMaterials createdBom = new BillOfMaterials("...");     // create new entity
em.persist(createdBom);  // createdBom is now managed and will be saved to database when the current JTA transaction completes

The entity lifecycle is managed by the underlying persistence provider.

  • New (transient): an entity is new if it has just been instantiated using the new operator, and it is not associated with a persistence context. It has no persistent representation in the database and no identifier value has been assigned.

  • Managed (persistent): a managed entity instance is an instance with a persistent identity that is currently associated with a persistence context.

  • Detached: the entity instance is an instance with a persistent identity that is no longer associated with a persistence context, usually because the persistence context was closed or the instance was evicted from the context.

  • Removed: a removed entity instance is an instance with a persistent identity, associated with a persistence context, but scheduled for removal from the database.

Deployment

The persistence.xml contains the persistence unit configuration (e.g. datasource name) and as described in the JPA 2.0 spec (section 8.2), the jar file or directory whose META-INF directory contains the persistence.xml file is termed the root of the persistence unit. In Java EE environments, the root of a persistence unit must be one of the following (quoted directly from the JPA 2.0 specification):

  • an EJB-JAR file

  • the WEB-INF/classes directory of a WAR file

  • a jar file in the WEB-INF/lib directory of a WAR file

  • a jar file in the EAR library directory

  • an application client jar file

The persistence.xml can specify either a JTA datasource or a non-JTA datasource. The JTA datasource is expected to be used within the EE environment (even when reading data without an active transaction). If a datasource is not specified, the default-datasource will instead be used (must be configured).

NOTE: Java Persistence 1.0 supported use of a jar file in the root of the EAR as the root of a persistence unit. This use is no longer supported. Portable applications should use the EAR library directory for this case instead.

Troubleshooting

The org.jboss.as.jpa logging can be enabled to get the following information:

  • INFO - when persistence.xml has been parsed, starting of persistence unit service (per deployed persistence.xml), stopping of persistence unit service

  • DEBUG - informs about entity managers being injected, creating/reusing transaction scoped entity manager for active transaction

  • TRACE - shows how long each entity manager operation took in milliseconds, application searches for a persistence unit, parsing of persistence.xml

To enable TRACE, open the as/standalone/configuration/standalone.xml (or as/domain/configuration/domain.xml) file. Search for <subsystem xmlns="urn:jboss:domain:logging:1.0"> and add the org.jboss.as.jpa category.  You need to change the console-handler level from INFO to TRACE

<subsystem xmlns="urn:jboss:domain:logging:1.0">
     <console-handler name="CONSOLE">
      <level name="TRACE" />
      ...
     </console-handler>

     </periodic-rotating-file-handler>
     <logger category="com.arjuna">
        <level name="WARN" />
     </logger>

     <logger category="org.jboss.as.jpa">
        <level name="TRACE" />
     </logger>

     <logger category="org.apache.tomcat.util.modeler">
        <level name="WARN" />
     </logger>
     ...

To see what is going on at the JDBC level, enable jboss.jdbc.spy DEBUG and add spy="true" to the datasource.

To troubleshoot issues with the Hibernate second level cache, try enabling trace for org.hibernate.SQL + org.hibernate.cache.infinispan + org.infinispan:

<subsystem xmlns="urn:jboss:domain:logging:1.0">
     <console-handler name="CONSOLE">
      <level name="TRACE" />
      ...
     </console-handler>

     </periodic-rotating-file-handler>
     <logger category="com.arjuna">
        <level name="WARN" />
     </logger>

     <logger category="org.hibernate.SQL">
        <level name="TRACE" />
     </logger>

     <logger category="org.hibernate">
        <level name="TRACE" />
     </logger>
      <logger category="org.infinispan">
        <level name="TRACE" />
     </logger>

     <logger category="org.apache.tomcat.util.modeler">
        <level name="WARN" />
     </logger>
     ...

Using the Hibernate 4 JPA persistence provider

Hibernate 4 is packaged with the AS and is the default persistence provider.

Using the Infinispan second level cache

To enable the second level cache with Hibernate 4, just set the hibernate.cache.use_second_level_cache property to true, as is done in the following example (also set the shared-cache-mode accordingly). By default the application server uses Infinispan as the cache provider for JPA applications, so you don't need specify anything on top of that:

<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="2lc_example_pu">
   <description>example of enabling the second level cache.</description>
   <jta-data-source>java:jboss/datasources/mydatasource</jta-data-source>
   <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
   <properties>
      <property name="hibernate.cache.use_second_level_cache" value="true"/>
   </properties>
</persistence-unit>
</persistence>

Here is an example of enabling the second level cache for a Hibernate native API hibernate.cfg.xml file:

<property name="hibernate.cache.region.factory_class" value="org.jboss.as.jpa.hibernate4.infinispan.InfinispanRegionFactory"/>
<property name="hibernate.cache.infinispan.cachemanager" value="java:jboss/infinispan/container/hibernate"/>
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>

The Hibernate native API application will also need a MANIFEST.MF:

Dependencies: org.infinispan,org.hibernate

Infinispan Hibernate/JPA second level cache provider documentation contains advanced configuration information but you should bear in mind that when Hibernate runs within JBoss Application Server 7, some of those configuration options, such as region factory, are not needed. Moreover, the application server providers you with option of selecting a different cache container for Infinispan via hibernate.cache.infinispan.container persistence property. To reiterate, this property is not mandatory and a default container is already deployed for by the application server to host the second level cache.

Replacing the current Hibernate 4.0.x jars with a newer version

Just update the current as7/modules/org/hibernate/main folder to contain the newer version (after stopping your AS7 server instance).  The following instructions assume you are bringing in Hibernate ORM 4.1.1 jars.

  1. Delete *.index files in as7/modules/org/hibernate/main and as7/modules/org/hibernate/envers/main folders.

  2. Backup the current contents of as7/modules/org/hibernate in case you make a mistake.

  3. Remove the older jars and copy new Hibernate jars into as7/modules/org/hibernate/main + as7/modules/org/hibernate/envers/main.

  4. Update the as7/modules/org/hibernate/main/module.xml + as7/modules/org/hibernate/envers/main/module.xml to name the jars that you copied in.

Updated as7/modules/org/hibernate/main/module.xml will look like (note that dependencies won't change):

<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ JBoss, Home of Professional Open Source.
  ~ Copyright 2011, Red Hat, Inc., and individual contributors
  ~ as indicated by the @author tags. See the copyright.txt file in the
  ~ distribution for a full listing of individual contributors.
  ~
  ~ This is free software; you can redistribute it and/or modify it
  ~ under the terms of the GNU Lesser General Public License as
  ~ published by the Free Software Foundation; either version 2.1 of
  ~ the License, or (at your option) any later version.
  ~
  ~ This software is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
  ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  ~ Lesser General Public License for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public
  ~ License along with this software; if not, write to the Free
  ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  -->

<!-- Represents the Hibernate 4.0.x module-->
<module xmlns="urn:jboss:module:1.1" name="org.hibernate">
    <resources>
        <resource-root path="hibernate-core-4.1.1.Final.jar"/>
        <resource-root path="hibernate-commons-annotations-4.0.1.Final.jar"/>
        <resource-root path="hibernate-entitymanager-4.1.1.Final.jar"/>
        <resource-root path="hibernate-infinispan-4.1.1.Final.jar"/>
        <!-- Insert resources here -->
    </resources>

    <dependencies>
       .
       .
       .
    </dependencies>
</module>

Updated as7/modules/org/hibernate/envers/module.xml will look like (note that dependencies won't change):

<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ JBoss, Home of Professional Open Source.
  ~ Copyright 2011, Red Hat, Inc., and individual contributors
  ~ as indicated by the @author tags. See the copyright.txt file in the
  ~ distribution for a full listing of individual contributors.
  ~
  ~ This is free software; you can redistribute it and/or modify it
  ~ under the terms of the GNU Lesser General Public License as
  ~ published by the Free Software Foundation; either version 2.1 of
  ~ the License, or (at your option) any later version.
  ~
  ~ This software is distributed in the hope that it will be useful,
  ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
  ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  ~ Lesser General Public License for more details.
  ~
  ~ You should have received a copy of the GNU Lesser General Public
  ~ License along with this software; if not, write to the Free
  ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  ~ 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  -->

<module xmlns="urn:jboss:module:1.1" name="org.hibernate.envers">
    <resources>
        <resource-root path="hibernate-envers-4.1.1.Final.jar"/>
        <!-- Insert resources here -->
    </resources>

    <dependencies>
    .
    .
    .
    </dependencies>
</module>

Packaging the Hibernate 3.5 or greater 3.x JPA persistence provider with your application

AS7 allows the packaging of Hibernate 3.5 (or greater) persistence provider jars with the application. The JPA deployer will detect the presence of a persistence provider in the application and jboss.as.jpa.providerModule needs to be set to hibernate3-bundled.

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="plannerdatasource_pu">
        <description>Hibernate 3 Persistence Unit.</description>
        <jta-data-source>java:jboss/datasources/PlannerDS</jta-data-source>
        <properties>
            <property name="hibernate.show_sql" value="false" />
            <property name="jboss.as.jpa.providerModule" value="hibernate3-bundled" />
        </properties>
    </persistence-unit>
</persistence>

The AS7 testsuite contains a test that packages jars from the Hibernate 3.6.5.Final jars in the ear lib.

Sharing the Hibernate 3.5 or greater JPA persistence provider between multiple applications

Applications can share the same Hibernate3 (for Hibernate 3.5 or greater) persistence provider by manually creating an org.hibernate:3 module (in the AS/modules folder). Steps to create the Hibernate3 module:

  1. In a command shell, go to the AS installation and change into the modules/org folder.
    cd AS/modules/org or cd AS\modules\org\hibernate

  2. Create folder for slot 3 to hold Hibernate 3
    mkdir 3
    cd 3

  3. Copy the Hibernate3 jars into this new AS/modules/org/hibernate/3 folder
    (hibernate3-core.jar, hibernate3-commons-annotations.jar, hibernate3-entitymanager.jar, dom4j.jar, slf4j.jar, slf4j-api.jar, commons-collections.jar, antlr.jar, slf4j-api.jar, commons-collections.jar, antlr.jar and any other jar needed for Hibernate 3).

  4. Create the AS/modules/org/hibernate/3/module.xml file with contents:

    <?xml version="1.0" encoding="UTF-8"?>
    <module xmlns="urn:jboss:module:1.0" name="org.hibernate" slot="3">
        <resources>
            <resource-root path="hibernate3-core.jar"/>
            <resource-root path="hibernate3-commons-annotations.jar"/>
            <resource-root path="hibernate3-entitymanager.jar"/>
            <resource-root path="javassist-3.12.0.GA.jar"/>
            <resource-root path="antlr-2.7.6.jar"/>  
            <resource-root path="commons-collections-3.1.jar"/>  
            <resource-root path="dom4j-1.6.1.jar"/>  
            <resource-root path="javassist-3.12.0.GA.jar"/>  
            <!-- Insert other Hibernate 3 jars to be used here -->
        </resources>
    
        <dependencies>
            <module name="org.jboss.as.jpa.hibernate" slot="3"/>
            <module name="asm.asm"/>
            <module name="javax.api"/>
            <module name="javax.persistence.api"/>
            <module name="javax.transaction.api"/>
            <module name="javax.validation.api"/>
            <module name="org.infinispan"/>
            <module name="org.javassist"/>
            <module name="org.slf4j"/>
        </dependencies>
    </module>

In your persistence.xml, you will refer to the Hibernate 3 persistence provider as follows:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="crm_pu">
        <description>CRM Persistence Unit.</description>
        <jta-data-source>java:jboss/datasources/CRMDS</jta-data-source>
        <properties>
            <property name="jboss.as.jpa.providerModule" value="org.hibernate:3" />
        </properties>
    </persistence-unit>
</persistence>

Using DataNucleus

Read the how to use DataNucleus with AS7 guide here.

Using Hibernate OGM

This section is a work in progress.

Example persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
  <persistence-unit name="MINIMAL">
    <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>

    <properties>
         <property name="jboss.as.jpa.classtransformer" value="false" />      
         <property name="jboss.as.jpa.adapterModule" value="org.jboss.as.jpa.hibernate:4"/>
    </properties>
  </persistence-unit>
</persistence>

The Hibernate ORM module needs to depend on OGM.  Change AS7/modules/org/hibernate/main/module.xml to:

 <?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.hibernate">
    <resources>
        <resource-root path="hibernate-core-4.1.6.Final.jar"/>
        <resource-root path="hibernate-entitymanager-4.1.6.Final.jar"/>
        <resource-root path="hibernate-infinispan-4.1.6.Final.jar"/>
        <!-- Insert resources here -->
    </resources>

    <dependencies>
        <module name="asm.asm"/>
        <module name="javax.api"/>
        <module name="javax.persistence.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.validation.api"/>
        <module name="org.antlr"/>
        <module name="org.apache.commons.collections"/>
        <module name="org.dom4j"/>
        <module name="org.infinispan" optional="true"/>
        <module name="org.javassist"/>
        <module name="org.jboss.as.jpa.hibernate" slot="4" optional="true"/>
        <module name="org.jboss.logging"/>
        <module name="org.hibernate.envers" services="import" optional="true"/>
        <module name="org.hibernate" slot="ogm" services="import"/>
    <module name="org.hibernate.commons-annotations"/>
    </dependencies>
</module>

The AS7/modules/org/hibernate/ogm folder should contain the OGM jars and the following module.xml:

 <?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.hibernate" slot="ogm">
    <resources>
        <resource-root path="hibernate-ogm-core-4.0.0-SNAPSHOT.jar"/>
    <resource-root path="hibernate-ogm-infinispan-4.0.0-SNAPSHOT.jar"/>
        <!-- Insert resources here -->
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="javax.persistence.api"/>
        <module name="javax.transaction.api"/>
        <module name="javax.validation.api"/>
        <module name="org.dom4j"/>
        <module name="org.infinispan" optional="true"/>
        <module name="org.jboss.as.jpa.hibernate" slot="4" optional="true"/>
        <module name="org.jboss.logging"/>
    <module name="org.hibernate.commons-annotations"/>
    <module name="org.hibernate" export="true"/>
    </dependencies>
</module>

Native Hibernate use

Applications that use the Hibernate API directly, are referred to here as native Hibernate applications. Native Hibernate applications, can choose to use the Hibernate jars included with JBoss AS or they can package their own copy of the Hibernate jars. Applications that utilize JPA will automatically have the JBoss AS Hibernate injected onto the application deployment classpath. Meaning that JPA applications, should expect to use the Hibernate jars included in JBoss AS.

Example MANIFEST.MF entry to add Hibernate dependency:

Manifest-Version: 1.0
...
Dependencies: org.hibernate

If you use the Hibernate native api in your application and also use the JPA api to access the same entities (from the same Hibernate session/EntityManager), you could get surprising results  (e.g. HibernateSession.saveOrUpdate(entity) is different than EntityManager.merge(entity).  Each entity should be managed by either Hibernate native api or JPA code.

Injection of Hibernate Session and SessionFactoryInjection of Hibernate Session and SessionFactory

You can inject a org.hibernate.Session and org.hibernate.SessionFactory directly, just as you can do with EntityManagers and EntityManagerFactorys.

import org.hibernate.Session;
import org.hibernate.SessionFactory;
@Stateful public class MyStatefulBean ... {
   @PersistenceContext(unitName="crm") Session session1;
   @PersistenceContext(unitName="crm2", type=EXTENDED) Session extendedpc;
   @PersistenceUnit(unitName="crm") SessionFactory factory;
}

Hibernate properties

AS7 automatically sets the following Hibernate (4.x) properties (if not already set in persistence unit definition):

Property

Purpose

hibernate.id.new_generator_mappings =true

New applications should let this default to true, older applications with existing data might need to set to false (see note below).  It really depends on whether your application uses the @GeneratedValue(AUTO) which will generates new key values for newly created entities.  The application can override this value (in the persistence.xml).

hibernate.transaction.jta.platform= instance of org.hibernate.service.jta.platform.spi.JtaPlatform interface

The transaction manager, user transaction and transaction synchronization registry is passed into Hibernate via this class.

hibernate.ejb.resource_scanner = instance of org.hibernate.ejb.packaging.Scanner interface

Instance of entity scanning class is passed in that knows how to use the AS annotation indexer (for faster deployment).

hibernate.transaction.manager_lookup_class

This property is removed if found in the persistence.xml (could conflict with JtaPlatform)

hibernate.session_factory_name = qualified persistence unit name

Is set to the application name + persistence unit name (application can specify a different value but it needs to be unique across all application deployments on the AS instance).

hibernate.session_factory_name_is_jndi = false

only set if the application didn't specify a value for hibernate.session_factory_name.

hibernate.ejb.entitymanager_factory_name =  qualified persistence unit name

Is set to the application name + persistence unit name (application can specify a different value but it needs to be unique across all application deployments on the AS instance).

In Hibernate 4.x, if new_generator_mappings is true:

  • @GeneratedValue(AUTO) maps to org.hibernate.id.enhanced.SequenceStyleGenerator

  • @GeneratedValue(TABLE) maps to org.hibernate.id.enhanced.TableGenerator

  • @GeneratedValue(SEQUENCE) maps to org.hibernate.id.enhanced.SequenceStyleGenerator

In Hibernate 4.x, if new_generator_mappings is false:

  • @GeneratedValue(AUTO) maps to Hibernate "native"

  • @GeneratedValue(TABLE) maps to org.hibernate.id.MultipleHiLoPerTableGenerator

  • @GeneratedValue(SEQUENCE) to Hibernate "seqhilo"

Persistence unit properties

The following properties are supported in the persistence unit definition (in the persistence.xml file):

Property

Purpose

jboss.as.jpa.providerModule

name of the persistence provider module (default is org.hibernate). Should be hibernate3-bundled if Hibernate 3 jars are in the application archive (adapterModule and adapterClass will automatically be set for hibernate3-bundled).  Should be application, if a persistence provider is packaged with the application.  See note below about some module names that are built in (based on the provider).

jboss.as.jpa.adapterModule

name of the integration classes that help the AS to work with the persistence provider. Current valid values are org.jboss.as.jpa.hibernate:4 (Hibernate 4 integration classes) and org.jboss.as.jpa.hibernate:3 (Hibernate 3 integration classes). Other integration adapter modules are expected to be added.

jboss.as.jpa.adapterClass

class name of the integration adapter. Current valid values are org.jboss.as.jpa.hibernate3.HibernatePersistenceProviderAdaptor and org.jboss.as.jpa.hibernate4.HibernatePersistenceProviderAdaptor.

jboss.as.jpa.managed

set to false to disable container managed JPA access to the persistence unit.  The default is true, which enables container managed JPA access to the persistence unit.  This is typically set to false for Seam 2.x + Spring applications.

jboss.as.jpa.classtransformer

set to false to disable class transformers for the persistence unit.  The default is true, which allows class enhancing/rewriting.  Hibernate also needs persistence unit property hibernate.ejb.use_class_enhancer to be true, for class enhancing to be enabled.

Determine the persistence provider module

As mentioned above, if the jboss.as.jpa.providerModule property is not specified, the provider module name is determined by the provider name specified in the persistence.xml.  The mapping is:

Provider Name

Module name

blank

org.hibernate

org.hibernate.ejb.HibernatePersistence

org.hibernate

org.hibernate.ogm.jpa.HibernateOgmPersistence

org.hibernate:ogm

oracle.toplink.essentials.PersistenceProvider

oracle.toplink

oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider

oracle.toplink

org.eclipse.persistence.jpa.PersistenceProvider

org.eclipse.persistence

org.datanucleus.api.jpa.PersistenceProviderImpl

org.datanucleus

org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider

org.datanucleus:appengine

org.apache.openjpa.persistence.PersistenceProviderImpl

org.apache.openjpa

Binding EntityManagerFactory to JNDI

By default JBoss AS7 does not bind the entity manager factory to JNDI. However, you can explicitly configure this in the persistence.xml of your application by setting the jboss.entity.manager.factory.jndi.name property. The value of that property should be the JNDI name to which the entity manager factory should be bound. Here's an example:

persistence.xml
<?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="myPU">
      <!-- If you are running in a production environment, add a managed
         data source, the example data source is just for proofs of concept! -->
      <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
      <properties>
         <!-- Bind entity manager factory to JNDI at java:jboss/myEntityManagerFactory -->
         <property name="jboss.entity.manager.factory.jndi.name" value="java:jboss/myEntityManagerFactory" />
      </properties>
   </persistence-unit>
</persistence>

Community

Many thanks to the community, for reporting issues, solutions and code changes. A number of people have been answering AS7 forum questions related to JPA usage. I would like to thank them for this, as well as those reporting issues. For those of you that haven't downloaded the AS source code and started hacking patches together. I would like to encourage you to start by reading Hacking on AS7. You will find that it easy very easy to find your way around the AS7/JPA/* source tree and make changes. The following list of contributors should grow over time, I hope to see more of you listed here.

People who have contributed to the AS7 JPA layer:

Hall of fame

For answering JPA related AS questions in the forums:

  • Prasad Deshpande has reported issues but more importantly, has been answering others JPA related questions as well.

If you see someone answering JPA related questions in the forums,or if I left you out (and you have been answering JPA questions), add the name to the above list.

JBoss.org Content Archive (Read Only), exported from JBoss Community Documentation Editor at 2020-03-13 13:28:16 UTC, last content change 2015-02-07 10:04:13 UTC.