JPA Tutorial

JPA is the Java Persistence API.As we know , most applications we are developing now a days are having a database , for managing the data. To  interact with data base from our application  , we need to write complex queries ,in a traditional approach . There are various Object relational Mapping (ORM) technologies(like Hibernate,TopLink)  to make the relational database transactions easier.These ORM technologies helping the developers by  mapping the relational data with Plain Old Java Objects(POJOs).JPA is the Standard persistence API specification.Now other ORM technologies like Hibernate are compliant with JPA specifications.(Hibernate is compliant to JPA specifications  from version 3.2 onwards.)So JPA is the reference Persistence implementation now a days.This chapter is a basic JPA Tutorial which discusses the fundamental concepts of JPA.

JPA was developed as part of JSR 220 : EJB 3.0  specifications. It simplified the complex entity bean development in EJB. But JPA can be used outside EJB container also. It can be used in stand alone applications also.

Overview to JPA

JPA Specifications are part of Java from Java EE 5 onwards.Before the introduction of JPA specifications , ORM technologies like Hibernate were there . After the release of JPA specifications , those technologies were standardized with JPA. In case of Hibernate , version 3.2 is the standardized version . From there onwards , each Hibernate release is conforming to JPA stands.

Now let us start our discussion on the key concepts of JPA.

1.Entities

An entity class is a class which can be considered as light weight persistent domain object. Each object of the entity class is considered as a row in a database table.Each entity class should be annotated with @Entity annotation. The attributes of entity class corresponds to various columns in the database table. The primary key attribute should be annotated with @Id annotation.

Requirements of an Entity class

1)@Entity annotation should be there

2)No argument constructor should be there(public or protected)

3)Entity classes can be sub classed to entity classes or non entity classes.An entity class can be extended from a non entity class.

4)An entity class should not be specified as final.Methods or persistent instance variables should not be declared as final.

5)It is desirable for the entity class to implement the Serializable interface. If the entity objects are sending remotely , then the instance should be Serializable.

The concept will be come clear once we look into a sample entity class.It is using JPA annotations for mapping. Optionally we can do the mapping via xml file also.

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity(name = "student")
public class Student implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String level;

public Student() {

}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

@Column(name = "name")
public void setName(String name) {
this.name = name;
}

public String getLevel() {
return level;
}

@Column(name = "level")
public void setLevel(String level) {
this.level = level;
}

}

  • @Entity annotation indicates that the class Student.java is an entity class. The emtity name is given in ‘name=”student’.If the entity name and table name are different then we need to use @Table annotation after @Entity
  • @Id indicates that the next attribute is the primary key.
  • @GeneratedValue specifies a strategy to allocate a unique value to the primary key attribute. There are 4 types of primary key generation strategies in JPA: AUTO,TABLE,SEQUENCE,IDENTITY. The default strategy is AUTO.
  • @Column annotation does the mapping between attributes to database columns.The ‘name’ part is optional. If not specified , the name of the attribute will be taken as column name.

Primary key Generation Strategies in JPA

  • GenerationType.AUTO :-This is the default key generation strategy. If we specify the strategy as AUTO , then the persistence provider is responsible for selecting the appropriate strategy . The selected strategy will be any one of the remaining 3 strategies , depending on the underlying database.
  • GenerationType.IDENTITY :-In this case , primary key will be generated by the database itself.The generated primary key will be unique in a particular table. In other words , the same primary  key value can be there in another tables.Supporting Database :    MsSQL , MySQL, DB2 versions from version 7.1 onwards.
  • GenerationType.SEQUENCE :- Some databases like Oracle has specific sequence generators for primary key generation. By specifying the strategy as SEQUENCE we are notifying the persistence provider to use the corresponding sequence generator  of the underlying the database.The sequence name also needs to be mentioned  using @SequenceGenerator annotation.                                                                                                                             Supporting Databases  :  PostgreSQL,Oracle , DB2 version 7.2 
  • GenerationType.TABLE :-This is the most portable way of primary key generation . In this case   the persistence provider needs to assign primary keys for the entity using an underlying database table to ensure uniqueness.

2)Persistence xml File

This is an xml file which contains the database configuration properties and corresponding values for those properties.A sample persistence.xml is shown here.

org.apache.openjpa.persistence.PersistenceProviderImpl com.jpa.entity.Student

The persistence.xml contains various persistent units. Persistent units contains the persistent provider details and various properties.In the above example , there is only one persistent unit which is using OpenJPA as provider implementation.The tag contains the annotated classes.The persistent unit property names can be either JPA specific property names  or persistence provider specific names.For example , to give database user name we can either use javax.persistence.jdbc.user property or openjpa.ConnectionUserName ,if we are using OpenJPA as implementation. A persistence.xml file contains any number of persistent units.The provider for each unit can be same or different.

3)JPA Transactions

There is a component EntityManager in JPA. The EntityManager manages all entity transactions.The following code snippet shows the usage of EntityManager.

EntityManagerFactory entityManagerFactory = Persistence
.createEntityManagerFactory("OpenJPASample");
entitymanager = entityManagerFactory.createEntityManager();
EntityTransaction transaction = entitymanager.getTransaction();
Student student = new Student();
student.setName("Karthik");
student.setLevel("H");
transaction.begin();
entitymanager.persist(student);
transaction.commit();

The EntityManaagerFactory is created from the persistent unit.Then an entity manager is created. Then the object transaction is created from the EntityManager.In the above code one Student object is created locally and the object is persisted using the EntityManager.

Java Persistence Query Language(JPQL)

It is a simplified query language. It can be considered as the object oriented version of SQL.In the coming chapters we will be discussing the important JPQL concepts and queries.

The concepts of programming with JPA will become clear once we discuss an example.

See related Discussions

JPA Example

The find() method in JPA

Updating a record using JPA

JPA Delete Example

JPQL

JPQL – Update Query Example

JPQL Delete Query Example

Caching

Overview to JPA Caching

Locking in JPA

Locking in JPA

Relational Mappings in JPA

One To One Mapping in JPA

One To Many mapping in JPA

Many To Many Mapping in JPA

Many To One Mapping in JPA