Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

JPA CRUD example

This is an example of how to perform CRUD functionality in JPA. The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications.

Here, we are using JPA to perform create, delete, update and delete methods, as shown below:

Employee Class

The Employee class is an entity class, annotated with the javax.persistence.Entity annotation. It uses the @Id annotation to define its id property.

package employeeDB;import javax.persistence.*;
 
@Entity
publicclass Employee {
 
    @Id String name;
    Double salary;
 
    public Employee()
    {
 
    }
 
    public Employee (String name, Double Salary)
    {

  this.name=name;

  this.salary=Salary;
    }
 
    publicvoid setSalary(Double Salary)
    {

  this.salary=Salary;
    }
 
    publicString toString()
    {

  return"Name: "+name+"nSalary: "+salary ;
    }
 
}

ExampleProgram

In the ExampleProgram we create four methods, displayAll(), insert(), delete(String name) and modify(String name, Double Salary) to perform the CRUD functionality. In all methods we use an EntityManager, using the createEntityManager() API method. The getTransaction().begin() and getTransaction().commit() methods are used before and after the EntityManager invokes a method so that a transaction begins and ends.

  • In displayAll() method we use the createQuery(java.lang.String qlString, java.lang.Class<T> resultClass) method to create an instance of TypedQuery for executing a Java Persistence query language statement. Then using the getResultList() method of Query we get the list of the results.
  • In insert() method a new object is writen to the database, using the persist(java.lang.Object entity) API method of EntityManager.
  • In delete(String name) method an Employee object can be retrieved using the find(java.lang.Class<T> entityClass, java.lang.Object primaryKey) API method of EntityManager. Then it can be removed using the remove(java.lang.Object entity) API method of EntityManager.
  • In modify(String name, Double Salary) method an Employee object can be retrieved using the find(java.lang.Class<T> entityClass, java.lang.Object primaryKey) API method of EntityManager. Then a field of the object can be modified using its setter.
  • package employeeDB;
     
    import javax.persistence.*;
    import java.util.*;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
     
    public class Main {
     
        /**
         * Displays all Employees in the Database
         */
        private static void displayAll()
        {
    
      em.getTransaction().begin();
    
      TypedQuery  e=em.createQuery(displayAllQuery, Employee.class);
    
      List <Employee> employees=e.getResultList();
    
      if(employees.size()>0)
    
      {
    for(Employee temp:employees)
    {
        System.out.println(temp);
        System.out.println();
    }
    System.out.println(employees.size()+" Employee Records Available...!");
      }
      else
    System.out.println("Database is Empty!");
      em.getTransaction().commit();
        }
     
        /**
         * Insets an Employee into the Database.
         */
        private static void insert()
        {
    System.out.print("Enter the number of Employees to be inserted: ");
    n=input.nextInt();
    em.getTransaction().begin();
    for(int i=0;i<n;i++)
    { 
        System.out.println("Enter the details of Employee "+(i+1)+": ");
        System.out.print("Name: ");
        //I use BufferedReader to read String and hence I need to 
        // Catch the IOException that it may throw
        try
        {
      name=bufferedReader.readLine();
        }
        catch (IOException e)
        {
      e.printStackTrace();
        }
        System.out.print("Salary: ");
        Salary=input.nextDouble();
        Employee emp=new Employee(name,Salary);
        em.persist(emp);
      //Store emp into Database
    }
      em.getTransaction().commit();
      System.out.println("n"+n+" employee record(s) Created!n");
      TypedQuery  count=em.createQuery(countQuery,Employee.class);
      System.out.println("n"+count.getSingleResult()+" employee record(s) Available in Database!n");
        }
        /**
         * Deletes the specified Employee from the database
         *@param name
         */
        private static void delete(String name)
        {
      em.getTransaction().begin();
      Employee e=(Employee) em.find(Employee.class, name);
       //Find Object to be deleted
      em.remove(e);
    
    //Delete the Employee from database
      System.out.printf("Employee %s removed from Database....",e.name);
      em.getTransaction().commit();
      //Display Number of Employees left
      TypedQuery  count=em.createQuery(countQuery,Employee.class);
      System.out.println("n"+count.getSingleResult()+" employee record(s) Available in Database!n");
       }
        /**
         * Changes salary of the specified employee to passed salary
         *@param name
         *@param Salary
         */
        private static void modify(String name,Double Salary)
        {
      em.getTransaction().begin();
      Employee e=(Employee) em.find(Employee.class, name);  //Find Employee to be modified
      e.setSalary(Salary);
        //Modify the salary
      em.getTransaction().commit();
      System.out.println("Modification Successful!n");
        }
       public static void main(String arg[])
        {
      System.out.println("Welcome to the Employee Database System!nn");
      do{    
    System.out.print("Menu: n 1. View DBn2. Insert n3. Delete n4. Modifyn5. ExitnEnter Choice...");
    int ch=input.nextInt();
    try{
        switch(ch)
        {
        case 1:
      displayAll();
      break;
        case 2:
      insert();
      break;
        case 3:
      System.out.print("Name of Employee to be Deleted2: ");
      name=bufferedReader.readLine();
      delete(name);
      break;
        case 4:
      System.out.print("Name of Employee to be Modified: ");
      name=bufferedReader.readLine();
      System.out.print("New Salary: ");
      Salary=input.nextDouble();
      modify(name,Salary);
      break;
        case 5:
      if(em!=null) em.close();
      //Close EntityManager
      if(emf!=null) emf.close();
      //Close EntityManagerFactory
      exit=true;
      break;
        }
    }
    catch (IOException e)
    {
       e.printStackTrace();
    }
      }while(!exit);
        }
        static EntityManagerFactory emf=Persistence.createEntityManagerFactory("empDB.odb");
        static EntityManager em=emf.createEntityManager();
        static Scanner input=new Scanner(System.in);
        static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
     
        static int n;
        static String name;
        static Double Salary;
        static boolean exit=false;
     
        //Query Repository
        static String countQuery="Select count(emp) from Employee emp";
        static String displayAllQuery="Select emp from Employee emp";
     }
    

     
    This was an example of how to perform CRUD functionality in JPA.

    Related Article:

    Reference: Java Persistence API: a quick intro… from our JCG partner Steve Robinson at Footy ‘n’ Tech blog

    Do you want to know how to develop your skillset to become a Java Rockstar?

    Subscribe to our newsletter to start Rocking right now!

    To get you started we give you two of our best selling eBooks for FREE!

    JPA Mini Book

    Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

    JVM Troubleshooting Guide

    The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

    Given email address is already subscribed, thank you!
    Oops. Something went wrong. Please try again later.
    Please provide a valid email address.
    Thank you, your sign-up request was successful! Please check your e-mail inbox.
    Please complete the CAPTCHA.
    Please fill in the required fields.
    Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
    All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
    Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
    Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
    Do you want to know how to develop your skillset and become a ...
    Java Rockstar?

    Subscribe to our newsletter to start Rocking right now!

    To get you started we give you two of our best selling eBooks for FREE!

    Get ready to Rock!
    You can download the complementary eBooks using the links below:
    Close