Home >> Enterprise Java >> jpa >> JPA CRUD example


JPA CRUD example


Here is the class that we will be using as the Entity Class….
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 ;
    }
 
}

Example Program
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!\n\n");
 
        do{    
 
            System.out.print("Menu: \n 1. View DB\n2. Insert \n3. Delete \n4. Modify\n5. Exit\nEnter 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";
 
}

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