Open In App

JPA – Inserting an Entity

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The JPA (Java Persistence API) is a Java specification for accessing, persisting, and maintaining data between Java objects and a relational database. It can provide a framework for assigning Java objects to database tables and simplify database operations in Java applications.

Inserting an entity into the database is the fundamental operation and the entity represents the data entity in the application, and it can typically be mapped to the database table. Inserting the entity involves creating a new record in the database table to store the entity data.

Importance of Inserting Entities

Inserting the entities is essential for persisting data to the database and it can maintain the state of the application data and it can allow the applications to store the user inputs and perform the data processing and also maintains the data consistency across the different transactions.

Key Terminologies:

  • Entity: This can represent a persistent data entity in an application and can often be mapped to a database table. The entity class can be assigned @Entity defined as an entity.
  • Entity Manager: This is the interface that can be used to interact with the persistence context, and can manage the lifecycle of entities, including tasks such as persistence, merge and removal, and querying.
  • Enhancements: Can be used to set off managed entity instances and these entity managers can use persistence to track changes being made to organizations and synchronize them with the database
  • Primary Key (ID): This can be a primary key that can uniquely identify any record in the table and in these entities, the primary key field can be described with @Id and can be a value itself.
  • Mapping annotations: These annotations are @Entity, @Id, @GeneratedValue, @OneToOne, @OneToMany, @ManyToMany. These are used to map entity classes and define relationships between them.
  • Relationships: It can be defined as the entities can have relationships with other entities such as one-to-one, many-to-one, and many-to-many and these are defined using the appropriate annotations.
  • Cascade Types: It can be defined as how entity lifecycles change the propagate from the parent entities to the child entities. Some common cascade types include the ALL, PERSIST, MERGE, REMOVE and REFRESH.
  • Persistence Unit: It is the logical grouping of the entity classes, and it is the configuration settings. It can be defined in the persistance.xml file and typically corresponds to the database.
  • JPQL: It can be defined as Java Persistence Query Language and it is the query language similar to the SQL but the operations on the entity objects rather than the database tables. It can be used to perform the database queries in the JPA.

Steps for Inserting an Entity

Step 1: We need to create the entity class that can represents the data you want to the persist into the database. Entity class is annotated with @Entity and define the fields of the entity class includes the primary key annotated with @Id.

Example:

@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;
private double price;

// Getters and Setters
}


Step 2: We can create the EntityManager interface can be used to the interact with persistence context and it can performs the database operations and also obtain the istance of EntityManager from the EntityManagerFactory.

EntityManagerFactory emf= Persistence.createEntityManagerFactory("jpa-example");
EntityManager em= entityManagerFactory.createEntityManager();


Step 3: Before the performing any database operations begins the transcation to be ensure that the operations are the atomic and consistent and start the new transcation using EntityTranscation interface.

EntityTransaction trs= entityManager.getTransaction();
trs.begin();


Step 4: We can use the persist( ) method of the EntityManager interface to the insert the entity into the database and this method can be add the entity to persistence context and it can schedule the insert operation for the entity in database up to the transaction commit.

Ex: Persist the Entity

Product product = new Product();
product.setName("Smart Phone");
product.setPrice(15000.0);

entityManager.persist(product);


Step 5: Once complete the database operation then commit the transaction to apply the changes of database. Now, we can commit the transaction using commit() method of the EntityTransaction interface.

Example: Commit the Transaction

transaction.commit();


Step 6: Close the EntityManager

entityManager.close();

By following the above steps, we can insert the entity into the database using JPA in the Java applications.

Project Implementation:

Step 1: First, we can create the JPA project using the IntellijIdea named as entity-demo of the project.

Step 2: Now, we can add the below dependencies into the JPA project.

Dependencies:

<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>

Once the project creation completed, then the file structure will look like the below image.

File Structure


Step 3: Open persistance.xml and put the below code for the MYSQL database configuration of the database.

XML
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
                                 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
  <persistence-unit name="jpa-example" transaction-type="RESOURCE_LOCAL">
    <class>Product</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/example"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.password" value=""/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
  </persistence-unit>
</persistence>

Step 4: Create the new Entity Java class for the creation of the entity and it named as Product.

Go to src > main > java > Product and put the below code.

Java
import jakarta.persistence.*;

// Entity annotation specifies that the class is an entity and is mapped to a database table
@Entity
public class Product {
    // Id annotation specifies the primary key of the entity
    @Id
    // GeneratedValue annotation provides the strategy for generating primary key values
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    // Name of the product
    private String name;
    
    // Price of the product
    private double price;

    // Getter method for retrieving the product id
    public Long getId() {
        return id;
    }

    // Setter method for setting the product id
    public void setId(Long id) {
        this.id = id;
    }

    // Getter method for retrieving the product name
    public String getName() {
        return name;
    }

    // Setter method for setting the product name
    public void setName(String name) {
        this.name = name;
    }

    // Getter method for retrieving the product price
    public double getPrice() {
        return price;
    }

    // Setter method for setting the product price
    public void setPrice(double price) {
        this.price = price;
    }
}


Step 5: Create the new Java class and named as the Main.

Go to src > main > java > Main and put the below code.

Java
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

public class Main {
    public static void main(String[] args) {
        // Obtain EntityManager instance
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpa-example");
        EntityManager em = emf.createEntityManager();

        // Begin transaction
        em.getTransaction().begin();

        // Create and persist Product entity
        Product product = new Product();
        product.setName("Laptop");
        product.setPrice(1000.0);
        em.persist(product);

        // Commit transaction
        em.getTransaction().commit();

        // Retrieve the persisted Product entity
        Product persistedProduct = em.find(Product.class, product.getId());

        // Print the details of the persisted Product entity
        System.out.println("Inserted Product Details:");
        System.out.println("ID: " + persistedProduct.getId());
        System.out.println("Name: " + persistedProduct.getName());
        System.out.println("Price: " + persistedProduct.getPrice());

        // Close EntityManager
        em.close();
        emf.close();
    }
}

pom.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>entity-demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>entity-demo</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
    <junit.version>5.9.2</junit.version>
  </properties>

  <dependencies>
<dependency>
      <groupId>org.hibernate.orm</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>6.0.2.Final</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.jaxb</groupId>
      <artifactId>jaxb-runtime</artifactId>
      <version>3.0.2</version>
    </dependency>
<dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
      <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.28</version>
      </dependency>

  </dependencies>

  <build>
    <plugins>
    </plugins>
  </build>
</project>


Step 6: Once the project is done, then run the application and we can get the output like the below image.

Output

If we follow the above steps, then we can successfully demonstrate Inserting the Entity into the JPA project.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads