Open In App

JPA – Finding an Entity

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

JPA in Java can be defined as the Java Persistence API(JPA). Entities are the basic building blocks that represent data in a database. Correctly retrieving entities from a database is an important part of any JPA application.

Finding an Entity in JPA involves taking data stored in a database and mapping it to the corresponding entity objects in the application.

Steps to Implement Finding an Entity in JPA

This process follows these fundamental steps:

1. Setting Up the Persistence Context

The persistence context establishes the connection with the database. It involves configuring the persistence.xml file or the equivalent configuration files to define the database connection properties, entity mapping, and the other relevant settings.

    <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>

2. Entity Manager Creation

The EntityManager interface, the central component in the JPA and it manages the lifecycle of the entities within the persistence context. To begin the entity retrieval process, it can instantiate the EntityManager using the EntityManagerFactory.

// EntityManagerFactory creation
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myPersistenceUnit");

// EntityManager instantiation
EntityManager entityManager = entityManagerFactory.createEntityManager();

3. Performing the Entity Retrieval

We can utilize the EntityManager’s find() method to the retrieve the based on the specified criteria. This method can accepts the entity class and primary key as the parameters. It can facilitating the efficient the retrieval of the single entities of the JPA applications.

// Entity retrieval
Product product = entityManager.find(Product.class, 1L);

4. Processing the Retrieved Entities

Once the entities are retrieved, we can be processed within the application logic. It may involve performing the additional operations, manipulating the data or presenting it to the user interface.

// Processing retrieved entity
if (product != null) {
System.out.println("Product Name: " + product.getName());
} else {
System.out.println("Product not found!");
}

These are the steps collectively from the foundation for the entity retrieval in the JPA application. It can enable the seamless interaction between the application and underlying the database of the application.

Project Implementation to demonstrate JPA Finding an entity

Below are the implementation steps to demonstrate the JPA Finding an entity.

Step 1: Create the new JPA project using the Intellj Idea named jpa-find-entity-demo.

After creating the project successfully, the folder structure will look like the below image.

Project Structure

file structure


Step 2: Open the pom.xml and add the below dependencies into the project.

Dependencies:

 <groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.2.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>3.0.2</version>
</dependency>


Step 3: Now, open the persistence.xml and write the below code into the project to configure the database.

XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="https://jakarta.ee/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence https://jakarta.ee/xml/ns/persistence/persistence_3_0.xsd"
             version="3.0">
  <persistence-unit name="example-unit">

    <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: In the model package, create a Java entity class named as Product.

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

Java
package model;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;

import java.math.BigDecimal;

@Entity
public class Product {
    @Id
    private Long id;
    private String name;

    @Column(nullable = false, columnDefinition = "DECIMAL(10,2) DEFAULT 0.00")
    private BigDecimal price;
  
    // Getters and setters
    // Constructor

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }



    public void setName(String name) {
        this.name = name;
    }
    public Product() {

    }

    public Product(Long id, String name, BigDecimal price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }
}


Step 5: Create a new Java class named as MainApplication.

Go to src > main > java > MainApplication and then write the below code there.

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

import java.math.BigDecimal;

public class MainApplication {
    public static void main(String[] args) {
        // Creating EntityManagerFactory
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit");
        EntityManager em = emf.createEntityManager();

        // Adding sample products
        em.getTransaction().begin();
        Product product1 = new Product(1L, "iPhone",new BigDecimal("1250000"));
        Product product2 = new Product(2L, "Samsung Galaxy",new BigDecimal("125800"));
        em.persist(product1);
        em.persist(product2);
        em.getTransaction().commit();

        // Finding entity
        Product foundProduct = em.find(Product.class, 1L);
        if (foundProduct != null) {
            System.out.println("Product found: " + foundProduct.getName());
        } else {
            System.out.println("Product not found.");
        }

        // Closing EntityManager and EntityManagerFactory
        em.close();
        emf.close();
    }
}
  • This MainApplication demonstrates entity management using JPA.
  • It creates an EntityManagerFactory and EntityManager.
  • It persists two sample Product entities into the database, retrieves a Product entity by its ID, and prints its name if found.
  • Finally, it closes the EntityManager and EntityManagerFactory to release resources.

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>jpa-find-entity-demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>jpa-find-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>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.28</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>  </dependencies>

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


Step 6: Once the project is completed, run the application and it will print the product found as output. Refer the below image for better understanding.

Output Screen

By the following the above steps, we can demonstrate the finding the entity of the JPA applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads