Writing first JPA 2.1 example

The article is all about creating your first application example in JPA 2.1. The article illustrates how to integrate libraries, remote repository and the Maven build tool in your application.

Writing first JPA 2.1 example

In this tutorial I will teach you how you can create your fist JPA 2.1 example. The JPA 2.1 libraries are available on the remote repository and the Maven build tool will able to download the JPA 2.1 libraries. So, for sake of simplicity we will use the Maven tool for this example.

You will be able to run the example easily using Maven 3 build tool. We have used the MySQL database for storing the data for this application. The MySQL database is very easy to use database and its free. You can easily download the MySQL database server and install on your computer for this example.

What is needed?

Following software/tools are need for developing the first JPA 2.1 example application:

Since we are using the Maven build tool, maven will take care of dependencies and download the libraries from the remote repositories. Maven 3 makes it easy to build and run the application easily.

Let's start developing our first JPA 2.1 example.

Step 1: Create database and table.

First of create the database. Following is the code to create the database:

create database jpa;

Now create the table using following SQL:

CREATE TABLE `products` (                                
            `id` int(11) NOT NULL AUTO_INCREMENT,                  
            `product_name` varchar(250) DEFAULT NULL,              
            `product_description` varchar(400) DEFAULT NULL,       
            `stock_qty` double(10,2) DEFAULT NULL,                 
            `price` double(10,2) DEFAULT NULL,                     
            PRIMARY KEY (`id`)                                     
   ) ENGINE=InnoDB;
Advertisement

Step 2: Create Model Class ( Entity class).

The Entity is simple a POJO class which contains the annotations for mapping to the relational database. The annotations defined in the javax.persistence.* package.

Here is the code of our entity class (Product.java):

package net.roseindia.model;

import javax.persistence.*;

/**
* @author Deepak Kumar
* More tutorials at http://www.roseindia.net
*/

@Entity
@Table(name="products")
public class Product {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	
	@Column(name="product_name")
	private String productName;
	
	@Column(name="product_description")
	private String productDescription;
	
	@Column(name="stock_qty")
	private Double stockQty;
	
	@Column(name="price")
	private Double price;

	public int getId() {
		return id;
	}

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

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getProductDescription() {
		return productDescription;
	}

	public void setProductDescription(String productDescription) {
		this.productDescription = productDescription;
	}

	public Double getStockQty() {
		return stockQty;
	}

	public void setStockQty(Double stockQty) {
		this.stockQty = stockQty;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}
	

}

Here we have used the following annotations:

@Entity: This annotation is used to make a class persistence class. The JPA environment will pick this class and register as persistence class.

@Table: This annotation is used to map the Entity to a table.

@Id: Makes a field entity's primary key

@Column(name="product_name"): This annotation is used to map a field to table's column. In this example this field is mapping to the 'product_name' column of the table.

Above class is an Entity class which maps to the 'products' table.

Step 3: Write persistence.xml file.

The persistence.xml is the configuration file in the XML format and should be included in the META-INF folder inside the JAR file of the project. It is the standard configuration file used in JPA applications.

The persistence.xml defines the persistence-unit(s) with unique name in the current classloader scope. A persistence unit defined in the persistence.xml represents the entities from a single data store. Here you can define your entities using <class>...</class> tag.

All the entity classes that defined in the persistence.xml file is managed by the EntityManager instances in Java program.

 Following code defines an Entity:

<class>net.roseindia.model.Product</class>

Here is the complete code of our persistence.xml file used in this project:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/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_1.xsd">
<!--
* @author Deepak Kumar
* More tutorials at http://www.roseindia.net
* -->

<persistence-unit name="psunit1">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
	<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
	<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa"/>
	<property name="javax.persistence.jdbc.user" value="root"/>
	<property name="javax.persistence.jdbc.password" value="root"/>
	<property name="eclipselink.ddl-generation" value="none"/>
	<property name="eclipselink.logging.level" value="INFO"/> 
</properties>

<class>net.roseindia.model.Product</class>

</persistence-unit>
</persistence>

In the above persistence.xml file we have defined the configuration for connecting it to the 'jpa' database which is running on 'localhost' machine. Your change all these values if your MySQL server is running on some other machine.

Sep 4: Write Java code to test the save (persist) operation.

Here is the Java code (AppTest.java) for testing the save operation:

package net.roseindia;

import net.roseindia.model.*;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.ParameterMode;
import javax.persistence.Persistence;
import javax.persistence.StoredProcedureQuery;
		/*
		//Compile mvn compile
		//Run: mvn exec:java -Dexec.mainClass="net.roseindia.AppTest"
		
		*/
/**
* @author Deepak Kumar
* More tutorials at http://www.roseindia.net
*/
		
public class AppTest {

	private static final String PERSISTENCE_UNIT_NAME = "psunit1";
	private static EntityManagerFactory factory;

	public static void main(String[] args) {
		factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
		EntityManager em = factory.createEntityManager();

		em.getTransaction().begin();
		
		Product product = new Product();
		product.setProductName("JPA 2.1 Book");
		product.setProductDescription("This is the latest book on JPA 2.1");
		product.setStockQty(100.00);
		product.setPrice(95.99);
		em.persist(product);
		em.getTransaction().commit();
		em.close();
		
	}
}

In the above code new "Product" entity is initialized and then persisted using the em.persist(product) method.

Step 5: Create pom.xml file and test the example.

First go the the fistexample directory where pom.xml file is present and then follow the following instructions. 0

To compile the code type:

mvn compile

Here is the screen shot: 1

and to run the application type following code on console:

mvn exec:java -Dexec.mainClass="net.roseindia.AppTest" 2

Here is the output of the program:

Download the JPA 2.1 First example code here. 3