Wednesday, 12 June 2013



The Java Persistence API (JPA) is the Java standard for mapping Java objects to a relational database. Even though proprietary mapping products like Hibernate and TopLink still exist, they are now focused on providing their functionality through the JPA API, allowing all applications to be portable across JPA implementations.

JPA permits the developer to work directly with objects rather than with SQL statements. The JPA implementation is typically called persistence provider.

The mapping between Java objects and database tables is defined via persistence metadata. The JPA provider will use the persistence metadata information to perform the correct database operations.

JPA typically defines the metadata via annotations in the Java class. Alternatively the metadata can be defined via XML or a combination of both. A XML configuration overwrites the annotations.

JPA defines a SQL-like Query language for static and dynamic queries.
Most JPA persistence provider offer the option to create automatically the database schema based on the metadata.


A class which should be persisted in a database it must be annotated with javax.persistence.Entity. Such a class is called Entity. JPA will create a table for the entity in your database. Instances of the class will be a row in the table.
All entity classes must define a primary key, must have a non-arg constructor and or not allowed to be final. Keys can be a single field or a combination of fields.
JPA allows to auto-generate the primary key in the database via the @GeneratedValue annotation.
By default, the table name corresponds to the class name. You can change this with the addition to the annotation @Table(name="NEWTABLENAME").

Persistence of fields

The fields of the Entity will be saved in the database. JPA can use either your instance variables (fields) or the corresponding getters and setters to access the fields. You are not allowed to mix both methods. If you want to use the setter and getter methods the Java class must follow the Java Bean naming conventions. JPA persists per default all fields of an Entity, if fields should not be saved they must be marked with @Transient.
By default each field is mapped to a column with the name of the field. You can change the default name via @Column (name="newColumnName").
The following annotations can be used.

Table 1. Annotations for fields / getter and setter
Identifies the unique ID of the database entry
Together with ID defines that this value is generated automatically.
Field will not be saved in database

Relationship Mapping

JPA allows to define relationships between classes, e.g. it can be defined that a class is part of another class (containment). Classes can have one to one, one to many, many to one, and many to many relationships with other classes.
A relationship can be bidirectional or unidirectional, e.g. in a bidirectional relationship both classes store a reference to each other while in an unidirectional case only one class has a reference to the other class. Within a bidirectional relationship you need to specify the owning side of this relationship in the other class with the attribute "mappedBy", e.g. @ManyToMany(mappedBy="attributeOfTheOwningClass".

Table 2. Relationship annotations

Entity Manager

The entity manager javax.persistence.EntityManager provides the operations from and to the database, e.g. find objects, persists them, remove objects from the database, etc. In a JavaEE application the entity manager is automatically inserted in the web application. Outside JavaEE you need to manage the entity manager yourself.
Entities which are managed by an Entity Manager will automatically propagate these changes to the database (if this happens within a commit statement). If the Entity Manager is closed (via close()) then the managed entities are in a detached state. If synchronize them again with the database an Entity Manager provides the merge() method.

Persistence Units

The EntityManager is created by the EntitiyManagerFactory which is configured by the persistence unit. The persistence unit is described via the file "persistence.xml" in the directory META-INF in the source folder. A set of entities which are logically connected will be grouped via a persistence unit. "persistence.xml" defines the connection data to the database, e.g. the driver, the user and the password.

JPA Architecture

  • Persistence: The javax.persistence.Persistence class contains static helper methods to obtain EntityManagerFactory instances in a vendor-neutral fashion.

  • EntityManagerFactory: The javax.persistence.EntityManagerFactory class is a factory for EntityManager s.

  • EntityManager : The javax.persistence.EntityManager is the primary JPA interface used by applications. Each EntityManager manages a set of persistent objects, and has APIs to insert new objects and delete existing ones. When used outside the container, there is a one-to-one relationship between an EntityManager and an EntityTransaction. EntityManagers also act as factories for Query instances.

  • Entity: Entites are persistent objects that represent datastore records.

  • EntityTransaction: Each EntityManager has a one-to-one relation with a single javax.persistence.EntityTransaction. EntityTransactions allow operations on persistent data to be grouped into units of work that either completely succeed or completely fail, leaving the datastore in its original state. These all-or-nothing operations are important for maintaining data integrity.

  • Query : The javax.persistence.Query interface is implemented by each JPA vendor to find persistent objects that meet certain criteria. JPA standardizes support for queries using both the Java Persistence Query Language (JPQL) and the Structured Query Language (SQL). You obtain Query instances from an EntityManager.

JPA Features

  • Simple POJO Persistence
    • No vendor-specific interfaces or classes

  • Supports rich domain models
    • No more anemic domain models
    • Multiple inheritance strategies
    • Polymorphic Queries
    • Lazy loading of associations

  • Rich Annotation Support
  • Pluggable persistence providers

JPA vs. Hibernate

JPA is a framework for managing relational data in Java applications, while Hibernate is a specific implementation of JPA (so ideally, JPA and Hibernate cannot be directly compared). In other words, Hibernate is one of the most popular frameworks that implements JPA. Hibernate implements JPA through Hibernate Annotation and EntityManager libraries that are implemented on top of Hibernate Core libraries. Both EntityManager and Annotations follow the lifecycle of Hibernate. The newest JPA version (JPA 2.0) is fully supported by Hibernate 3.5. JPA has the benefit of having an interface that is standardized, so the developer community will be more familiar with it than Hibernate. On the other hand, native Hibernate APIs can be considered more powerful because its features are a superset of that of JPA.



  1. Nice info regarding java persistence api My sincere thanks for sharing this post Please Continue to share this kind of post
    Java Training in Chennai

  2. nice blog has been shared by you. before i read this blog i didn't have any knowledge. but now i got some knowledge so keep on sharing such kind of an interesting blogs.
    java training in chennai

  3. Really it is a fantastic blog.You are a skilled blogger.I read your blog completely it is very nice.Thanks for sharing.keep sharing more blogs.

    Core Java Online Training


Find me on Facebook! Follow me on Twitter!