Hibernate.orgCommunity Documentation

Chapter 4. Tutorial Using the Java Persistence API (JPA)

Table of Contents

4.1. persistence.xml
4.2. The annotated entity Java class
4.3. Example code
4.4. Take it further!

This tutorial is located within the download bundle under entitymanager.


The previous tutorials used the Hibernate-specific hibernate.cfg.xml configuration file. JPA, however, defines a different bootstrap process that uses its own configuration file named persistence.xml. This bootstrapping process is defined by the JPA specification. In Java™ SE environments the persistence provider (Hibernate in this case) is required to locate all JPA configuration files by classpath lookup of the META-INF/persistence.xml resource name.

persistence.xml files should provide a unique name for each persistence unit. Applications use this name to reference the configuration when obtaining an javax.persistence.EntityManagerFactory reference.

The settings defined in the properties element are discussed in Section 2.1, “The Hibernate configuration file”. Here the javax.persistence-prefixed varieties are used when possible. Notice that the remaining Hibernate-specific configuration setting names are now prefixed with hibernate..

Additionally, the class element functions the same as in Section 3.1, “The Hibernate configuration file”.

The entity is exactly the same as in Section 3.2, “The annotated entity Java class”

The previous tutorials used the Hibernate APIs. This tutorial uses the JPA APIs.

Notice again that the persistence unit name is org.hibernate.tutorial.jpa, which matches Example 4.1, “persistence.xml

The code is similar to Example 2.5, “Saving entities”. An javax.persistence.EntityManager interface is used instead of a org.hibernate.Session interface. JPA calls this operation persist instead of save.

Again, the code is pretty similar to Example 2.6, “Obtaining a list of entities”.

Practice Exercises

  • Develop an EJB Session bean to investigate implications of using a container-managed persistence context (javax.persistence.EntityManager). Try both stateless and stateful use-cases.