News Stay informed about the latest enterprise technology news and product updates.

The JPA and Hibernate CRUD operations example

There are many classes and interfaces that make up the JPA and Hibernate API, and the sheer volume of development options can overwhelm even the most seasoned software developer. But as complex and comprehensive as the Java Persistence API is, most database interactions revolve around a very small number of functions, namely the create, retrieve, update and delete functions known as CRUD.

In order to create a Hiberante and JPA CRUD based application, there are relatively few classes and interfaces that the developer needs to know. Knowledge of these classes can be acquired quickly, and with this knowledge, a programmer becomes capable of creating powerful applications that cover the vast majority of an application’s database driven use cases. In this Hibernate and JPA CRUD tutorial will demonstrate how to do exactly that.

CRUD overview

On a previous tutorial I demonstrated the basics of Hibernate transaction management with the JPA EntityManager class. In that JPA tutorial we focused solely on the creation part of the CRUD quadfecta. This JPA and Hibernate CRUD example will pick up from where that example left off and create a new class with all four JPA CRUD operations:

  1. Create – insert a new record in the database  with a new, unique primary key
  2. Retrieve – pull a record from the database based on a unique property such as the primary key
  3. Update – change the properties of a database record that already exists
  4. Delete – remove a record from the database permanently

The JPA CRUD class

The new class to be created will be named JpaCrudExample, the skeleton of which follows. We will slowly fill the methods of this class in as the JPA CRUD example tutorial progresses.

Notice that the main method contains four static methods:

  1. JpaCrudExample.createRecord()
  2. JpaCrudExample.retrieveRecord()
  3. JpaCrudExample.updateRecord()
  4. JpaCrudExample.deleteRecord()
JPA CRUD operations

The four basic CRUD operations

These four records are currently uncommented. However, as you progress through the tutorial, you may want to comment out some of the static methods listed here so that errors don’t occur while testing. For example, if the updateRecord() method is called on a record where the primary key of interest has been deleted by a previous test of the deleteRecord() method, a runtime error will occur.

Here is the skeleton code for the CRUD application we will incrementally build over the course of this tutorial.

package com.mcnz.jpa.examples;

import java.util.*;
import javax.persistence.*;

public class JpaCrudExample {

  public static void main(String[] args) throws Exception {
    JpaCrudExample.createRecord();
    JpaCrudExample.retrieveRecord();
    JpaCrudExample.updateRecord();
    JpaCrudExample.deleteRecord();
  }

  public static void createRecord() { }
  public static void retrieveRecord() { }
  public static void updateRecord() { }
  public static void deleteRecord() { }

}

The JPA create operation

The create method was coded and explained in a previous tutorial, so we will populate the createRecord method with a quick copy and paste of that code:

public static void createRecord() {
 EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-tutorial");
 EntityManager entityManager = emf.createEntityManager();

 entityManager.getTransaction().begin();

 Player p = new Player();
 p.setPassword("my-password");
 p.setName("Julie");
 p.setTest("Tester!!!");

 entityManager.persist(p);

 entityManager.getTransaction().commit();
}

The retrieve CRUD operation

When this code runs, a new record is created in the database, likely with a primary key of 1 if this is the first time you have written to the database. To retrieve this record, we simply pass the primary key to the EntityManager’s find method. This returns the instance.

public static void retrieveRecord() {
 EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-tutorial");
 EntityManager entityManager = emf.createEntityManager();

 entityManager.getTransaction().begin();
 Long key = Long.valueOf(1);
 Player p = entityManager.find(Player.class, key);
 System.out.println(p.getName());

 entityManager.getTransaction().commit();
}

The update CRUD operation

To update an entity, all you need to do is retrieve it from the MySQL database and change some of its instance variables before the transaction commits. So the following code, which is only one line of code different from the retrieveRecord method, will update the name of record 1 from Julie to Karen.

public static void retrieveRecord() {
 EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-tutorial");
 EntityManager entityManager = emf.createEntityManager();

 entityManager.getTransaction().begin();
 Long key = Long.valueOf(2);
 Player p = entityManager.find(Player.class, key);
 //System.out.println(p.getName());
 p.setName("Karen");

 entityManager.getTransaction().commit();
}

The CRUD delete operation

To delete a record from the database, simply load the record of interest and then pass it to the  remove method of the Hibernate SessionFactory based EntityManager. In this case, we pull the record with the primary key of 1 from the database and then permanently delete it.

public static void deleteRecord() {

 EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-tutorial");
 EntityManager entityManager = emf.createEntityManager();

 entityManager.getTransaction().begin();
 Long key = Long.valueOf(2);
 Player p = entityManager.find(Player.class, key);
 entityManager.remove(p);

 entityManager.getTransaction().commit();

}

And that the essence of the Hiberante CRUD operations performed using the latest version of the Java Persistence API.

There are further nuances that each of these methods could employ. In future JPA tutorials we will look at updating a transient entity, or using the JPA Criteria API to query the database. NamedQueries and JPQL are other ways to query a database and retrieve records. But when you’r learning a technology, starting off simple is best, and this JpaCrudExample class covers the basics.

Supporting JPA code

Originally introduced in the JPA dev environment setup tutorial, the Person class used in this example is as follows:

package com.mcnz.jpa.examples;
import javax.persistence.*;

@Entity 
public class Player {

  @Id @GeneratedValue
  private Long id;
  private String name;
  private String password;
  private String test;

  public String getTest() {
    return test;
  }
  public void setTest(String test) {
    this.test = test;
  }
  public Long getId() {
   return id;
  }
  public void setId(Long id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
}

This JPA CRUD example also used the following persistence.xml file. You can toggle the comment on the database generation action depending upon whether you want JPA table creation enabled or not.

<?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://xmlns.jcp.org/xml/ns/persistence 
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

  <persistence-unit name="jpa-tutorial">
  <class>com.mcnz.jpa.examples.Player</class>
  <properties>
    <!-- property name="javax.persistence.jdbc.driver" value=" javax.persistence.jdbc.driver"/> -->
    <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/hibernate_examples"/>
    <property name="javax.persistence.jdbc.user" value="root"/>
    <property name="javax.persistence.jdbc.password" value="password"/>
    <property name = "hibernate.show_sql" value = "true" />
    <property name = "hibernate.format_sq" value = "true" />
    <!--property name = "javax.persistence.schema-generation.database.action" value="drop-and-create"/ -->
  </properties>
</persistence-unit>

</persistence>

You can find the source code for this example on GitHub.

 

 

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

SearchAppArchitecture

SearchSoftwareQuality

SearchCloudComputing

SearchSecurity

SearchAWS

Close