jpa

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

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button