×
☰ See All Chapters

JPA CRUD (Create, Read, Update, Delete) Methods and Example

In this tutorial we will learn how to perform CRUD (Create, Read, Update, and Delete) operation in JPA and the methods used for CRUD operation. First will learn the methods used in CRUD operation. Below table explains the methods used for CRUD operation.

Result

Method

Description

Insert

void

persist(Object entity)

First entity class object is assigned with an identifier (internally assigned by JPA or programmer given value). This entity class object is then persisted. Returns void.

Update

Object ref =

 

merge(Object entity)

 

Merge the state of the given entity into the current persistence context. Returns an updated persistent instance.

When we try to update an object which is not yet been assigned identity earlier, which means trying to merge fresh new entity object will persist a new record to database.

Reading single row

Object ref =

 

find(Class clazz, Object id)

Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance.

Parameters:

Class clazz – Argument should be Class object of the class (persistent class) which represents required Table in DB.  Class object represents the runtime class of the object.

Example:

         Class.forName("com.java4coding.Employee")

          Or

          Employee.class

Object id identity value of the record which we want. This can be primitive value also, in such cases Autoboxing happens.

There other overloaded find() methods present in the API to read the single record from database. Refer the JPA javadocs for the details.

Delete

void

remove(Object entity)

Remove the entity instance. Trying to remove an instance which is not there in database will be considered as transient object and JPA will remove this transient object.

 

JPA CRUD example

Database script

 

CREATE  TABLE `EMPLOYEE` (  

`empid` INT NOT NULL ,  

`firstname` VARCHAR(45) NULL ,  

`lastname` VARCHAR(45) NULL ,  

`email` VARCHAR(45) NULL ,  

PRIMARY KEY (`empid`) );

 

pom.xml

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">

        <modelVersion>4.0.0</modelVersion>

        <groupId>com.manum.hassan</groupId>

        <artifactId>JPACRUDExample</artifactId>

        <packaging>jar</packaging>

        <version>1.0-SNAPSHOT</version>

        <name>JPACRUDExample</name>

        <url>https://maven.apache.org</url>

        <dependencies>

                <dependency>

                        <groupId>junit</groupId>

                        <artifactId>junit</artifactId>

                        <version>3.8.1</version>

                        <scope>test</scope>

                </dependency>

                <dependency>

                        <groupId>org.eclipse.persistence</groupId>

                        <artifactId>javax.persistence</artifactId>

                        <version>2.0.0</version>

                </dependency>

 

                <dependency>

                        <groupId>org.hibernate</groupId>

                        <artifactId>hibernate-entitymanager</artifactId>

                        <version>4.2.8.Final</version>

                </dependency>

 

                <dependency>

                        <groupId>mysql</groupId>

                        <artifactId>mysql-connector-java</artifactId>

                        <version>8.0.11</version>

                </dependency>

        </dependencies>

</project>

 

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>

<persistence xmlns="https://java.sun.com/xml/ns/persistence"

        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="https://java.sun.com/xml/ns/persistence

             https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"

        version="2.0">

 

        <persistence-unit name="JPACRUD">

                <provider>org.hibernate.ejb.HibernatePersistence</provider>

                <properties>

                        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" />

                        <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" />

                        <property name="hibernate.connection.username" value="root" />

                        <property name="hibernate.connection.password" value="root" />

                        <property name="hibernate.archive.autodetection" value="class" />

                        <property name="hibernate.show_sql" value="true" />

                        <property name="hibernate.format_sql" value="true" />

                        <property name="hbm2ddl.auto" value="update" />

                </properties>

        </persistence-unit>

</persistence>

 

Employee.java

package com.java4coding;

 

import java.io.Serializable;

 

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

 

@Entity

@Table(name = "EMPLOYEE")

public class Employee implements Serializable {

 

        @Id

        private int empId;

 

        private String email;

 

        private String firstname;

 

        private String lastname;

 

        public Employee() {

        }

 

        public int getEmpId() {

                return empId;

        }

 

        public void setEmpId(int empId) {

                this.empId = empId;

        }

 

        public String getEmail() {

                return email;

        }

 

        public void setEmail(String email) {

                this.email = email;

        }

 

        public String getFirstname() {

                return firstname;

        }

 

        public void setFirstname(String firstname) {

                this.firstname = firstname;

        }

 

        public String getLastname() {

                return lastname;

        }

 

        public void setLastname(String lastname) {

                this.lastname = lastname;

        }

 

        @Override

        public String toString() {

                return "Employee [empId=" + empId + ", email=" + email + ", firstname=" + firstname + ", lastname=" + lastname + "]";

        }

}

 

 

Test.java

package com.java4coding;

 

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

 

import com.java4coding.Employee;

 

public class Test {

        public static void main(String[] args) {

 

                // Create EntityManagerFactory

                EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPACRUD");

 

                // Create Entity

                Employee employee1 = new Employee();

                employee1.setFirstname("Manu");

                employee1.setLastname("Manjunatha");

                employee1.setEmail("manu.m@java4coding.com");

                employee1.setEmpId(1);

                // Create EntityManager

                EntityManager em = emf.createEntityManager();

 

                // Persist entity

                em.getTransaction().begin();

                em.persist(employee1);

                em.getTransaction().commit();

 

                // Retrieve entity

                employee1 = em.find(Employee.class, 1);

                System.out.println(employee1);

 

                // Update entity

                em.getTransaction().begin();

                employee1.setEmail("feedback@java4coding.com");

                System.out.println("Updated Employee is: " + employee1);

                em.getTransaction().commit();

               

                //Updating through merge method

                Employee employee2 = new Employee();

                employee2.setEmail("manu.m@java4coding.com");

                employee2.setEmpId(1);

               

                em.getTransaction().begin();

                em.merge(employee2);

                em.getTransaction().commit();

               

                // Remove entity

                em.getTransaction().begin();

                em.remove(employee1);

                em.getTransaction().commit();

 

                // Check whether entity is removed or not

                employee1 = em.find(Employee.class, 1);

                System.out.println("Employee after removal: " + employee1);

               

        }

}

 

 

Project Directory Structure

 

jpa-crud-methods-and-example-0
 

Output

Hibernate:

    insert

    into

        EMPLOYEE

        (email, firstname, lastname, empId)

    values

        (?, ?, ?, ?)

Employee [empId=1, email=manu.m@java4coding.com, firstname=Manu, lastname=Manjunatha]

Updated Employee is: Employee [empId=1, email=feedback@java4coding.com, firstname=Manu, lastname=Manjunatha]

Hibernate:

    update

        EMPLOYEE

    set

        email=?,

        firstname=?,

        lastname=?

    where

        empId=?

Hibernate:

    update

        EMPLOYEE

    set

        email=?,

        firstname=?,

        lastname=?

    where

        empId=?

Hibernate:

    delete

    from

        EMPLOYEE

    where

        empId=?

Hibernate:

    select

        employee0_.empId as empId1_0_0_,

        employee0_.email as email2_0_0_,

        employee0_.firstname as firstnam3_0_0_,

        employee0_.lastname as lastname4_0_0_

    from

        EMPLOYEE employee0_

    where

        employee0_.empId=?

Employee after removal: null

 


All Chapters
Author