JPA 2.1 CRUD examples

JPA 2.1 CRUD examples that illustrates how to perform CRUD operations against database.


Learn how to create CRUD operation examples in JPA 2.1

In this section you will learn how to create example program that forms CRUD operations against database. The CRUD application (example) in JPA is very important topic which a beginner should learn first.

What is CRUD operations in JPA?

The CRUD stands for Create, Retrieve (Read), Update and Delete operations on an Entity. From Java program you can perform these operations on your Entity. The EntityManager, em represents a JPA link to the relational database which can be used to perform CRUD operations on the Entity objects.

In JPA the EntityManager is an interface which is associated with a persistence context. It is used to interact with the persistence context. Here are few important methods of EntityManager, em, which is used to perform the CRUD operations.

persist(Object entity):  This method is used to persist a managed Entity.

remove(Object entity): This method is used to remove an Entity from the persistence context.

merge(T entity): This method is used to save the current state of Entity to the persistence context.

find(Class<T> entityClass, Object primaryKey): This method is used to load an Entity based on its primary key.

You can check the JPA 2.1 API for more details about the different methods of EntityManager interface.

JPA CRUD Example

Basic Concepts of JPA

Let's learn some of the basic concepts of JPA before actually developing the examples. Following 4 concepts you should understand about JPA:

  • EntityManager - The EntityManager is an interface (comes with JPA API) that manages the state of an Entity.
  • Persistence Unit - The Persistence Unit is simply the Entity classes which is to be managed by the EntityManager instance.
  • Persistence Context - The PersistenceContext is the managed set of Entities and each entity is identified by its primary key.
  • Managed Entities -  These are the Entities which managed by the persistence context if they are part of Persistence Context.

Transaction Management

For managing the transaction you can use the em.getTransaction().begin(); and em.getTransaction().commit(); methods.

Let's start developing the program

We use the same table described in the last tutorial Writing first JPA 2.1 example. If don't have the table script check the tutorial Writing first JPA 2.1 example and create the table "products".

Create Operation example in JPA

Step 1: Create Model class - We will use the same model class used in the Writing first JPA 2.1 example tutorial.

Here is the code of our entity class (

package net.roseindia.model;

import javax.persistence.*;

* @author Deepak Kumar
* More tutorials at

public class Product {
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
	private String productName;
	private String productDescription;
	private Double stockQty;
	private Double price;

	public int getId() {
		return id;

	public void setId(int 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;


Step 2: Create JPA configuration file persistence.xml file. We will use the persistence.xml file from our previous tutorial Writing first JPA 2.1 example.

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="" 
* @author Deepak Kumar
* More tutorials at
* -->

<persistence-unit name="psunit1">
	<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"/> 



Step 3: Writing the Create JPA operations code.

In case of Create operation we simple creates a new instance of "Product" entity and sets the values using setter methods. After that we simply calls the em.persist(product); method to persist the entity.

Following code example creates 10 entities and saves into database:

	//Create and Persist 10 Objects
	for(int i=1;i<=10;i++){
		Product product = new Product();
		product.setProductName("Java Book No. "+i);
		product.setProductDescription("This is the Book No. "+i);

Step 4: JPA Retrieve operation.

To Retrieve the entities from the persistence store JPQL is used. Here is the query which used:

Query query = em.createQuery("SELECT o FROM Product o");

Here is the complete example of JPA retrieve operation:

//Select all the record from student table
Query query = em.createQuery("SELECT o FROM Product o");
List lst = query.getResultList();
Iterator it = lst.iterator();
while (it.hasNext()){
	Product product = (Product);
	System.out.print("Id: "+product.getId());
	System.out.print("Product Name: "+product.getProductName());
	System.out.println("Product Description: "+product.getProductDescription());
	System.out.println("Product Qty: "+product.getStockQty());
	System.out.println("Product Price: "+product.getPrice());


Step 5: JPA update example

Here we first loads the entity using following code:

Product product = em.find(Product.class,1);

then updates the state of the object and with the help of following code updates into database:

product.setProductDescription("Product description Updated");

Here is the complete code of the JPA Update operation:

/* Update Example */
//Load and update Entity Eample
Product product = em.find(Product.class,1);
product.setProductDescription("Product description Updated");

Step 6: JPA delete example

The em.remove(prodObj); method is used to remove an entity from persistence store. Here is the complete code of the process:

/* Delete Example */
Product prodObj = em.find(Product.class,2);

Step 7: Compiling and testing the example

To compile use the following command:

mvn compile

To run the example use the following code:

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

Here is the screen shot that shows the data in the database table after this operation:

Download the source code of JPA 2.1 CRUD operation tutorial.

Read more JPA 2.1 tutorials.


Share on Google+Share on Google+

JPA 2.1 CRUD examples

Posted on: November 28, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: JPA 2.1 CRUD examples  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image