Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

First Steps in Java Persistence API (JPA)

In this tutorial, we shall take a dive into the background details of the Java Persistence API. This will be followed by the initial steps to give you a heads up as to what it really is.

The use of databases in applications is probably the most important part of backend operations. This involves large amounts of storage and retrieval of data. While there are several technologies that handle this task, developers do face hassles when trying to perform operations connected to databases efficiently. Now, databases also have their own language for regular operations that take place, i.e. SQL (made up of DDL and DML), the use of JPA has also been pretty popular. JPA allows one to avoid writing in DDL (Data Definition Language) or DML (Data Manipulation Language) and can be replaced by writing XML mapping or just Java annotations. Also, when one needs to perform queries, JPQL (Java Persistence Query Language) can be used for the purpose instead of having to depend on SQL.

Java developers also tend to use plenty of code when it comes interacting with any database. However, with JPA, this reduces on a significant scale. On a general note, JPA turns out to be rather simple, clean and is also less intensive when compared to mappings written using JDBC (Java Database Connectivity), SQL and handwritten mappings.

What is Java Persistence API?

The process by which Java objects are mapped to the database tables and vice-versa is called as ORM or Object Relational Mapping. In this regard, Java Persistence API happens to be a one possible approach to ORM. It must also be noted that JPA merely happens to be a specification and there are many implementations possible. Some of the popular ones are EclipseLink, Hibernate, Apache OpenJPA, etc.

Using JPA, one can store, map, retrieve and update data from Java objects and also the other way round. As already stated earlier, JPA allows the coder to work with objects directly rather than make of SQL statements. This collection of classes and methods are provided by Oracle Corporation.

Mapping between Java objects and that if database tables happens via persistence method. The JPA provider makes use of persistence metadata for performing operations. Annotations are used by JPA to define metadata. XML may also be used for defining metadata.

Where to use Java Persistence API?

In order to reduce the burden that comes with writing code for relational object management, the ‘JPA Provider’ framework can be used instead. This allows for easier interaction with the database. Sp, JPA is helpful when it comes to using Object Relational Mapping.

Providers of Java Persistence API

JPA belongs to the open source category and several enterprise vendors are known to contribute to it. Some of the well-known vendors are Eclipse, Oracle and Redhat. Some popular products are –

  • Eclipselink
  • Toplink
  • Hibernate
  • Spring Data JPA

Architecture of JPA

The JPA acts as a means for the storage of business entities as relational entities. It defines an entity in the form of Plain Old Java Object (POJO) and manages it with relations.

We shall now take a look at JPA’s class level architecture that shows the core classes and interfaces.

  • EntityManagerFactory – This is the EntityManager’s factory class that is known to create and manage several instances of it.
  • EntityManager – This is basically an interface meant for managing persistence operations on objects. It is known to work like factory for query instance.
  • Entity – These are persistence objects. They are stored as records in the database.
  • EntityTransaction – This has a one-one relationship with the EntityManager. The EntityTransaction class maintains operations for every EntityManager.
  • Persistence – To obtain instance of EntityManagerFactory, this class contains static methods.
  • Query – This is an interface that is implemented by every JPA vendor to get relational objects that meet certain criteria.

These interfaces and classes are meant for storing entities in a database as records.

System Requirements for JPA

  • JDK 1.5 or higher
  • 1GB of RAM
  • Windows XP or Linux

We shall now process with the steps for the installation.

Installation of JPA

The installation and integration of JPA with one’s running Java environment is rather simple and can be done in a few steps.

The first step is to check if the Java installation is correctly done in your machine. This can be done by opening the command prompt and then executing the following command

\>java -version

In case you do not already have Java installed in your machine, you can do so downloading it from Oracle’s Java page.

Following this, one need to setup the Java Environment, which can be done by making the JAVA_HOME variable to point to the directory where Java has been installed.

Now, we shall learn the way to install JPA using Eclipse link. A folder framework needs to be maintained here so it is good to use an IDE. You can download the Eclipse IDE from https://www.eclipse.org/downloads/ and then install it in your machine.

Once you have finished installing Eclipse, we move towards Eclipse link. This is a library and can be added in the following steps –

  • Create a new JPA project by choosing File, followed by New and then JPA Project in the IDE.
  • A dialog box with named JPA project will show up where you need to enter the name of the project, JPAEclipselink and then Next.
  • Click on the download library option in the user library section.
  • Select the latest version of the Eclipselink library and then proceed with Next.
  • Accept the presented terms and click on Finish.
  • The files will be downloaded after which you can click on Finish.
  • You will now get the project file in the Package Explorer of Eclipse IDE. You can then extract all the files.

Addition of MySQL connector the project

We are considering MySQL database for database operation here. Thus, we need mysql connector jar in order to interact with the Java program.

  • Go to Project Properties and then Java Build Path by right clicking. A dialog box appears where you need to click Add External Jars.
  • Then go to the jar location in your system and select and then open it.
  • In the Properties dialog box. Click on OK. This will add the MySQL connector jar for the project and database operation can be performed.

Employee management using Java Persistence API

We shall now go through an example that will showcase the use of JPA.

The models in this project are –

Model

  • Employ.java

Persistence

  • Persist.xml

Service

  • CreateEmploy.java
  • UpdateEmploy.java

Creation of Entities

Entities are basically Models. In this case, we shall we using Employ as the entity, which will have id, name, sal, and deg as attributes, it will also have a constructor and setter and getter methods for these attributes.

Listing 1. Employ.java

package mrbool.eclipselink.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Employ {
 
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)       
   private int id;
   private String name;
   private double sal;
   private String deg;   
   public Employ(int id, String name, double sal, String deg) {
      super( );
      this.id = id;
      this.name = name;
      this.sal = sal;
      this.deg = deg;
   }
   public Employ( ) {
      super();
   }
   public int getid( ) {
      return id;
   }   
   public void setid(int eid) {
      this.id = id;
   }   
   public String getname( ) {
      return name;
   }   
   public void setname(String name) {
      this.name = name;
   }
   public double getSal ( ) {
      return sal;
   }
   
   public void setSal (double sal) {
      this.sal = sal;
   }
   public String getDeg( ) {
      return deg;
   }   
   public void setDeg(String deg) {
      this.deg = deg;
   }   
   @Override
   public String toString() {
      return "Employee [Id=" + id + ", Name=" + name + ", Salary=" + sal + ", deg=" + deg + "]";
   }
}

In the code, we have made use of the annotation @Entity to make this POJO class as an entity.

Now, we shall create a database for relational entity and will register it in the Persist.xml file. The MySQL workbench needs to be opened and the following command needs to be executed –

?> create database jpadb 
use jpadb

Listing 2. Persist.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
   http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">   
   <persistence-unit name="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">   
      <class> eclipselink.entity.Employ</class>
 
      <properties>
         <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpadb"/>
         <property name="javax.persistence.jdbc.user" value="root"/>
         <property name="javax.persistence.jdbc.password" value="root"/>
         <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
         <property name="eclipselink.logging.level" value="FINE"/>
         <property name="eclipselink.ddl-generation" value="create-tables"/>
      </properties>      
   </persistence-unit>
</persistence>

This is a very crucial model foe the concept of JPA. Here, we register the database and also specify the entity class.

In the above XML file, tag is specifies the name for the JPA persistence. The tag is meant to define the entity class along with the package name. The tag defines the properties, and tag defines every property, such as the likes of database registration, username, and password. These are the Eclipselink properties.

Persistence Operations

Persistence operations are those that perform load/store tasks and are used against the database. In the package hierarchy, we shall now create the various service classes.

Listing 3. CreateEmploy.java

package mrbool.eclipselink.service;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persist;
import eclipselink.entity.Employ;
public class CreateEmploy {
   public static void main( String[ ] args ) {   
      EntityManagerFactory emfactory = Persist.createEntityManagerFactory( "Eclipselink_JPA" );      
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );
 
      Employ employee = new Employ( ); 
      employee.setid( 101 );
      employee.setname( "Ravi" );
      employee.setSalary( 60000 );
      employee.setDeg( "Technical Support" );      
      entitymanager.persist( employee );
      entitymanager.getTransaction( ).commit( );
      entitymanager.close( );
      emfactory.close( );
   }
}

In the above code, thecreateEntityManagerFactory()is for creating a persistence unit. This is accomplished by providing the same name which we provide for persistence-unit in persist.xml file. The the entitymanger instance is created by the entitymanagerfactory object making use fo the createEntityManager()method. The entitytransaction instance is created by the entitymanager object for transaction management. By making use of the entitymanager object, we persist entities into the database.

Now, open the SQL workbench and execute the following –

use jpadb
select * from employee

The database table will show the following –

Id

Name

Salary

Deg

101

Ravi

60000

Technical Support

Table 1. Output table

Listing 4. UpdateEmploy.java

package mrbool.eclipselink.service;
 
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persist;
import eclipselink.entity.Employ;
public class UpdateEmploy {
   public static void main( String[ ] args ) {
      EntityManagerFactory emfactory = Persist.createEntityManagerFactory( "Eclipselink_JPA" );      
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );
      Employee employee = entitymanager.find( Employ.class, 101 );      
      //before updating
      System.out.println( employee );
      employee.setSalary( 69000 );
      entitymanager.getTransaction( ).commit( );      
      //after updating
      System.out.println( employee );
      entitymanager.close();
      emfactory.close();
   }
}

Here, we simply update the employee details by obtaining the record from the database, making the changes and then committing it to the database again.

When you compile and execute the command –

?> use jpadb
select * from employee

You shall get the following table –

Id

Name

Salary

Deg

101

Ravi

69000

Technical Support

Table 2. Output table with modified data

Similarly, we can perform other Persistence operations, such as finding employee or even deleting employee details from the database.

Conclusion

In this tutorial, we have leant about the background concerning Java Persistence API and how it aids in carrying out persistence operations that help coders perform database operations in a relatively simple manner.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login