JPA CRUD (Create, Retrieve, Update and Delete) Operation


Download Demo

We can perform CRUD (Create, Retrieve, Update and Delete) operation on an object with the help of EntityManager interface.


JPA Insertion (Create) Example


In this example inserting two data first one is Ravindra and second one is Mala.

private void create() {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    //first data
    Emp e1 = new Emp();
    e1.setName("Ravindra");
    em.persist(e1);
    // second data
    Emp e2 = new Emp();
    e2.setName("Mala");
    em.persist(e2);
    em.getTransaction().commit();
    em.close();
    System.out.println("Data Inserted");
}

JPA Fetch (retrieve) Example


In this example, I am fetching record by primary key (ID)

private void retrieveById() {
    EntityManager em = emf.createEntityManager();
    Emp e = em.find(Emp.class, 1);
    System.out.println("ID: " + e.getId() + ", Name: " + e.getName());
}

JPA Fetch all data Example


In this example, I am inserting two data first one is Ravindra and second one is Mala.
private void retrieveAll() {
    EntityManager em = emf.createEntityManager();
    Query query = em.createQuery("from Emp e");
    List<Emp> list = query.getResultList();
    for (Emp e : list) {
        System.out.println("ID: " + e.getId() + ", Name: " + e.getName());
    }
}

JPA Update Example


In this example, I am inserting two data first one is Ravindra and second one is Mala.
private void update() {
    EntityManager em = emf.createEntityManager();
    Emp e = em.find(Emp.class, 1);
    em.getTransaction().begin();
    e.setName("Sahil");
    em.getTransaction().commit();
    em.close();
    System.out.println("Data is updated");
}

JPA Delete Example


In this example, I am inserting two data first one is Ravindra and second one is Mala.
private void delete() {
    EntityManager em = emf.createEntityManager();
    Emp e = em.find(Emp.class, 1);
    em.getTransaction().begin();
    em.remove(e);
    em.getTransaction().commit();
    em.close();
    System.out.println("Data is updated");
}

Result...


emp (Table)
id name
1 Ravindra

Download Demo