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.

 Java |  copy code |? 
01
import java.io.Serializable;
02
import javax.persistence.Column;
03
import javax.persistence.Entity;
04
import javax.persistence.GeneratedValue;
05
import javax.persistence.GenerationType;
06
import javax.persistence.Id;
07
 
08
@Entity(name = "student")
09
public class Student implements Serializable {
10
 
11
    /**
12
     *
13
     */
14
    private static final long serialVersionUID = 1L;
15
    @Id
16
    @GeneratedValue(strategy = GenerationType.AUTO)
17
    private int id;
18
    private String name;
19
    private String level;
20
 
21
    public Student() {
22
 
23
    }
24
 
25
    public int getId() {
26
        return id;
27
    }
28
 
29
    public void setId(int id) {
30
        this.id = id;
31
    }
32
 
33
    public String getName() {
34
        return name;
35
    }
36
 
37
    @Column(name = "name")
38
    public void setName(String name) {
39
        this.name = name;
40
    }
41
 
42
    public String getLevel() {
43
        return level;
44
    }
45
 
46
    @Column(name = "level")
47
    public void setLevel(String level) {
48
        this.level = level;
49
    }
50
 
51
}

  • @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.

 Java |  copy code |? 
01
<?xml version="1.0" encoding="UTF-8"?>
02
<persistence version="2.0"
03
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
05
    <persistence-unit name="OpenJPASample"
06
        transaction-type="RESOURCE_LOCAL">
07
        <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
08
        <class>com.jpa.entity.Student</class>
09
        <properties>
10
            <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema" ></property>
11
            <property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/mysampledb" ></property>
12
            <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver" ></property>
13
            <property name="javax.persistence.jdbc.user" value="" ></property>
14
            <property name="javax.persistence.jdbc.password" value="" ></property>
15
            <property name="openjpa.RuntimeUnenhancedClasses" value="supported" ></property>
16
        </properties>
17
    </persistence-unit>
18
</persistence>

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.

 Java |  copy code |? 
01
EntityManagerFactory entityManagerFactory = Persistence
02
                .createEntityManagerFactory("OpenJPASample");
03
        entitymanager = entityManagerFactory.createEntityManager();
04
        EntityTransaction transaction = entitymanager.getTransaction();
05
        Student student = new Student();
06
        student.setName("Karthik");
07
        student.setLevel("H");
08
        transaction.begin();
09
        entitymanager.persist(student);
10
        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

Tagged with 

One thought on “JPA Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>