Red Hat Training

A Red Hat training course is available for Red Hat JBoss Enterprise Application Platform

13.2. Java Persistence API (JPA)

13.2.1. About JPA

The Java Persistence API (JPA) is the standard for using persistence in Java projects. Java EE 6 applications use the Java Persistence 2.0 specification, documented here:
Hibernate EntityManager implements the programming interfaces and life-cycle rules defined by the specification. It provides JBoss EAP 6 with a complete Java Persistence solution.
JBoss EAP 6 is 100% compliant with the Java Persistence 2.0 specification. Hibernate also provides additional features to the specification.
To get started with JPA and JBoss EAP 6, refer to the bean-validation, greeter, and kitchensink quickstarts: Section, “Access the Quickstarts”.

13.2.2. Hibernate EntityManager

Hibernate EntityManager implements the programming interfaces and life-cycle rules defined by the JPA 2.0 specification. It provides JBoss EAP 6 with a complete Java Persistence solution.
For more information about Java Persistence or Hibernate, refer to the Section 13.2.1, “About JPA” and Section 13.1, “About Hibernate Core”.

13.2.3. Getting Started Create a JPA project in Red Hat JBoss Developer Studio


This example covers the steps required to create a JPA project in Red Hat JBoss Developer Studio.

Procedure 13.1. Create a JPA project in Red Hat JBoss Developer Studio

  1. In the Red Hat JBoss Developer Studio window, click FileNewProject. Find JPA in the list, expand it, and select JPA Project. You are presented with the following dialog.
  2. Enter a Project name.
  3. Select a Target runtime. If no target runtime is available, follow these instructions to define a new server and runtime: Section, “Add the JBoss EAP Server Using Define New Server”.
  4. Under JPA version, ensure 2.1 is selected.
  5. Under Configuration, choose Basic JPA Configuration.
  6. Click Finish.
  7. If prompted, choose whether you wish to associate this type of project with the JPA perspective window. Create the Persistence Settings File in Red Hat JBoss Developer Studio


This topic covers the process for creating the persistence.xml file in a Java project using Red Hat JBoss Developer Studio.

Procedure 13.2. Create and Configure a new Persistence Settings File

  1. Open an EJB 3.x project in Red Hat JBoss Developer Studio.
  2. Right click the project root directory in the Project Explorer panel.
  3. Select NewOther....
  4. Select XML File from the XML folder and click Next.
  5. Select the ejbModule/META-INF folder as the parent directory.
  6. Name the file persistence.xml and click Next.
  7. Select Create XML file from an XML schema file and click Next.
  8. Select from the Select XML Catalog entry list and click Next.
  9. Click Finish to create the file.
The persistence.xml has been created in the META-INF/ folder and is ready to be configured. An example file is available here: Section, “Example Persistence Settings File” Example Persistence Settings File

Example 13.1. persistence.xml

<persistence xmlns=""
   <persistence-unit name="example" transaction-type="JTA">
         <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
         <property name="" value="create-drop"/>
</persistence> Create the Hibernate Configuration File in Red Hat JBoss Developer Studio


This topic covers the process for creating the hibernate.cfg.xml file in a Java project using Red Hat JBoss Developer Studio.

Procedure 13.3. Create a New Hibernate Configuration File

  1. Open a Java project in Red Hat JBoss Developer Studio.
  2. Right click the project root directory in the Project Explorer panel.
  3. Select NewOther....
  4. Select Hibernate Configuration File from the Hibernate folder and click Next.
  5. Select the src/ directory and click Next.
  6. Configure the following:
    • Session factory name
    • Database dialect
    • Driver class
    • Connection URL
    • Username
    • Password
  7. Click Finish to create the file.
The hibernate.cfg.xml has been created in the src/ folder. An example file is available here: Section, “Example Hibernate Configuration File”. Example Hibernate Configuration File

Example 13.2. hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"



        <!-- Datasource Name -->
        <property name="connection.datasource">ExampleDS</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.region.factory_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Update the database schema on startup -->
        <property name="">update</property>

        <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>



13.2.4. Configuration Hibernate Configuration Properties

Table 13.1. Hibernate Java Properties

Property Name Description
The classname of a Hibernate org.hibernate.dialect.Dialect. Allows Hibernate to generate SQL optimized for a particular relational database.
In most cases Hibernate will be able to choose the correct org.hibernate.dialect.Dialect implementation, based on the JDBC metadata returned by the JDBC driver.
Boolean. Writes all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug.
Boolean. Pretty print the SQL in the log and console.
Qualify unqualified table names with the given schema/tablespace in generated SQL.
Qualifies unqualified table names with the given catalog in generated SQL.
The org.hibernate.SessionFactory will be automatically bound to this name in JNDI after it has been created. For example, jndi/composite/name.
Sets a maximum "depth" for the outer join fetch tree for single-ended associations (one-to-one, many-to-one). A 0 disables default outer join fetching. The recommended value is between 0 and 3.
Sets a default size for Hibernate batch fetching of associations. The recommended values are 4, 8, and 16.
Sets a default mode for entity representation for all sessions opened from this SessionFactory. Values include: dynamic-map, dom4j, pojo.
Boolean. Forces Hibernate to order SQL updates by the primary key value of the items being updated. This will result in fewer transaction deadlocks in highly concurrent systems.
Boolean. If enabled, Hibernate will collect statistics useful for performance tuning.
Boolean. If enabled, generated identifier properties will be reset to default values when objects are deleted.
Boolean. If turned on, Hibernate will generate comments inside the SQL, for easier debugging. Default value is false.
Boolean. This property is relevant when using @GeneratedValue. It indicates whether or not the new IdentifierGenerator implementations are used for javax.persistence.GenerationType.AUTO, javax.persistence.GenerationType.TABLE and javax.persistence.GenerationType.SEQUENCE. Default value is true.
Chooses the org.hibernate.cfg.NamingStrategy implementation when using Hibernate EntityManager. This class is deprecated and this property is only provided for backward compatibility. This property must not be used with hibernate.ejb.naming_strategy_delegator.
If the application does not use EntityManager, follow the instructions here to configure the NamingStrategy: Hibernate Reference Documentation - Implementing a Naming Strategy.
Specifies an org.hibernate.cfg.naming.NamingStrategyDelegator implementation for database objects and schema elements when using Hibernate EntityManager. This property has the following possible values.
  • org.hibernate.cfg.naming.LegacyNamingStrategyDelegator: This is the default value. This class is deprecated and is only provided for backward compatibility.
  • org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator: This is the preferred value. It generates default table and column names that comply with the JPA specification. It allows for specification of both the entity and foreign key class names. This class only affects entities that are mapped using Java annotations or JPA XML descriptors. Entities mapped using hbm.xml are not affected,
  • If you prefer, you can configure a custom class that implements org.hibernate.cfg.naming.ImprovedNamingStrategyDelegator


This property must not be used with hibernate.ejb.naming_strategy. It is a temporary replacement for org.hibernate.cfg.NamingStrategy to address its limitations. A more comprehensive solution is planned for Hibernate 5.0 that replaces both org.hibernate.cfg.NamingStrategy and org.hibernate.cfg.naming.NamingStrategyDelegator.
If the application does not use EntityManager, follow the instructions here to configure the NamingStrategy: Hibernate Reference Documentation - Implementing a Naming Strategy.


For, new applications should keep the default value of true. Existing applications that used Hibernate 3.3.x may need to change it to false to continue using a sequence object or table based generator, and maintain backward compatibility. Hibernate JDBC and Connection Properties

Table 13.2. Properties

Property Name Description
A non-zero value that determines the JDBC fetch size (calls Statement.setFetchSize()).
A non-zero value enables use of JDBC2 batch updates by Hibernate. The recommended values are between 5 and 30.
Boolean. Set this property to true if the JDBC driver returns correct row counts from executeBatch(). Hibernate will then use batched DML for automatically versioned data. Default value is to false.
Select a custom org.hibernate.jdbc.Batcher. Most applications will not need this configuration property.
Boolean. Enables use of JDBC2 scrollable resultsets by Hibernate. This property is only necessary when using user-supplied JDBC connections. Hibernate uses connection metadata otherwise.
Boolean. This is a system-level property. Use streams when writing/reading binary or serializable types to/from JDBC.
Boolean. Enables use of JDBC3 PreparedStatement.getGeneratedKeys() to retrieve natively generated keys after insert. Requires JDBC3+ driver and JRE1.4+. Set to false if JDBC driver has problems with the Hibernate identifier generators. By default, it tries to determine the driver capabilities using connection metadata.
The classname of a custom org.hibernate.connection.ConnectionProvider which provides JDBC connections to Hibernate.
Sets the JDBC transaction isolation level. Check java.sql.Connection for meaningful values, but note that most databases do not support all isolation levels and some define additional, non-standard isolations. Standard values are 1, 2, 4, 8.
Boolean. This property is not recommended for use. Enables autocommit for JDBC pooled connections.
Specifies when Hibernate should release JDBC connections. By default, a JDBC connection is held until the session is explicitly closed or disconnected. The default value auto will choose after_statement for the JTA and CMT transaction strategies, and after_transaction for the JDBC transaction strategy.
Available values are auto (default), on_close, after_transaction, after_statement.
This setting only affects Session returned from SessionFactory.openSession. For Session obtained through SessionFactory.getCurrentSession, the CurrentSessionContext implementation configured for use controls the connection release mode for that Session.
Pass the JDBC property <propertyName> to DriverManager.getConnection().
Pass the property <propertyName> to the JNDI InitialContextFactory. Hibernate Cache Properties

Table 13.3. Properties

Property Name Description
The classname of a custom CacheProvider.
Boolean. Optimizes second-level cache operation to minimize writes, at the cost of more frequent reads. This setting is most useful for clustered caches and, in Hibernate3, is enabled by default for clustered cache implementations.
Boolean. Enables the query cache. Individual queries still have to be set cacheable.
Boolean. Used to completely disable the second level cache, which is enabled by default for classes that specify a <cache> mapping.
The classname of a custom QueryCache interface. The default value is the built-in StandardQueryCache.
A prefix to use for second-level cache region names.
Boolean. Forces Hibernate to store data in the second-level cache in a more human-friendly format.
Setting used to give the name of the default org.hibernate.annotations.CacheConcurrencyStrategy to use when either @Cacheable or @Cache is used. @Cache(strategy="..") is used to override this default. Hibernate Transaction Properties

Table 13.4. Properties

Property Name Description
The classname of a TransactionFactory to use with Hibernate Transaction API. Defaults to JDBCTransactionFactory).
A JNDI name used by JTATransactionFactory to obtain the JTA UserTransaction from the application server.
The classname of a TransactionManagerLookup. It is required when JVM-level caching is enabled or when using hilo generator in a JTA environment.
Boolean. If enabled, the session will be automatically flushed during the before completion phase of the transaction. Built-in and automatic session context management is preferred.
Boolean. If enabled, the session will be automatically closed during the after completion phase of the transaction. Built-in and automatic session context management is preferred. Miscellaneous Hibernate Properties

Table 13.5. Properties

Property Name Description
Supply a custom strategy for the scoping of the "current" Session. Values include jta, thread, managed, custom.Class.
Chooses the HQL parser implementation: org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory or org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory.
Used to map from tokens in Hibernate queries to SQL tokens (tokens might be function or literal names). For example, hqlLiteral=SQL_LITERAL, hqlFunction=SQLFUNC.
Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly. Property value options are validate, update, create, create-drop
Comma-separated names of the optional files containing SQL DML statements executed during the SessionFactory creation. This is useful for testing or demonstrating. For example, by adding INSERT statements, the database can be populated with a minimal set of data when it is deployed. An example value is /humans.sql,/dogs.sql.
File order matters, as the statements of a given file are executed before the statements of the following files. These statements are only executed if the schema is created (i.e. if is set to create or create-drop).
The classname of a custom ImportSqlCommandExtractor. Defaults to the built-in SingleLineSqlCommandExtractor. This is useful for implementing a dedicated parser that extracts a single SQL statement from each import file. Hibernate also provides MultipleLinesSqlCommandExtractor, which supports instructions/comments and quoted strings spread over multiple lines (mandatory semicolon at the end of each statement).
Boolean. This is a system-level property, which cannot be set in the hibernate.cfg.xml file. Enables the use of bytecode manipulation instead of runtime reflection. Reflection can sometimes be useful when troubleshooting. Hibernate always requires either cglib or javassist even if the optimizer is turned off.
Both javassist or cglib can be used as byte manipulation engines. The default is javassist. Property value is either javassist or cglib Hibernate SQL Dialects


The hibernate.dialect property should be set to the correct org.hibernate.dialect.Dialect subclass for the application database. If a dialect is specified, Hibernate will use sensible defaults for some of the other properties. This means that they do not have to be specified manually.

Table 13.6. SQL Dialects (hibernate.dialect)

RDBMS Dialect
DB2 org.hibernate.dialect.DB2Dialect
DB2 AS/400 org.hibernate.dialect.DB2400Dialect
DB2 OS390 org.hibernate.dialect.DB2390Dialect
Firebird org.hibernate.dialect.FirebirdDialect
FrontBase org.hibernate.dialect.FrontbaseDialect
H2 Database org.hibernate.dialect.H2Dialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Informix org.hibernate.dialect.InformixDialect
Ingres org.hibernate.dialect.IngresDialect
Interbase org.hibernate.dialect.InterbaseDialect
Mckoi SQL org.hibernate.dialect.MckoiDialect
Microsoft SQL Server 2000 org.hibernate.dialect.SQLServerDialect
Microsoft SQL Server 2005 org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect
Microsoft SQL Server 2012 org.hibernate.dialect.SQLServer2008Dialect
MySQL5 org.hibernate.dialect.MySQL5Dialect
MySQL5 with InnoDB org.hibernate.dialect.MySQL5InnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle 9i org.hibernate.dialect.Oracle9iDialect
Oracle 10g org.hibernate.dialect.Oracle10gDialect
Oracle 11g org.hibernate.dialect.Oracle10gDialect
Pointbase org.hibernate.dialect.PointbaseDialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
PostgreSQL 9.2 org.hibernate.dialect.PostgreSQL82Dialect
Postgres Plus Advanced Server org.hibernate.dialect.PostgresPlusDialect
Progress org.hibernate.dialect.ProgressDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Sybase org.hibernate.dialect.SybaseASE15Dialect
Sybase 15.7 org.hibernate.dialect.SybaseASE157Dialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect

13.2.5. Second-Level Caches About Second-Level Caches

A second-level cache is a local data store that holds information persisted outside the application session. The cache is managed by the persistence provider, improving run-time by keeping the data separate from the application.
JBoss EAP 6 supports caching for the following purposes:
  • Web Session Clustering
  • Stateful Session Bean Clustering
  • SSO Clustering
  • Hibernate Second Level Cache
Each cache container defines a "repl" and a "dist" cache. These caches should not be used directly by user applications. Configure a Second Level Cache for Hibernate

This topic covers the configuration requirements for enabling Infinispan to act as the second level cache for Hibernate.

Procedure 13.4. Create and Edit the hibernate.cfg.xml file

  1. Create the hibernate.cfg.xml file

    Create the hibernate.cfg.xml in the deployment's classpath. For specifics, refer to Section, “Create the Hibernate Configuration File in Red Hat JBoss Developer Studio” .
  2. Add these lines of XML to the hibernate.cfg.xml file in your application. The XML needs to be inside the <session-factory> tags:
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
  3. Add one of the following to the <session-factory> section of the hibernate.cfg.xml file:
    • If the Infinispan CacheManager is bound to JNDI:

      <property name="hibernate.cache.region.factory_class">
      <property name="hibernate.cache.infinispan.cachemanager">
    • If the Infinispan CacheManager is standalone:

      <property name="hibernate.cache.region.factory_class">

Infinispan is configured as the Second Level Cache for Hibernate.