Spring Data JPA findById() Method Example

In this blog post, we will demonstrate how to use the findById() method in Spring Data JPA to fetch or retrieve an entity by ID from the database.

Understanding findById()

findById() is a method from the CrudRepository interface in Spring Data JPA. It's designed to fetch a single entity based on its primary key. The beauty lies in its return type: Optional<T>. This is a java.util.Optional, which means the method might or might not return a result. This helps in gracefully handling the scenario where a record with the given ID doesn't exist.

Method Signature:

Optional<T> findById(ID id);

  • T is the domain type the repository manages. 
  • ID is the type of the id of the entity the repository manages.

In this example, we will use the Product entity to save and retrieve to/from the MySQL database.

Maven Dependencies

First, you need to add the below dependencies to your Spring boot project:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>

Create Product Entity

Let's first create a Product entity that we are going to save and retrieve to/from the MySQL database:

package net.javaguides.springdatajpacourse.entity;

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import jakarta.persistence.*;
import java.math.BigDecimal;
import java.util.Date;

@Entity
@Table(name="products")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "sku")
    private String sku;

    @Column(name = "name")
    private String name;

    @Column(name = "description")
    private String description;

    @Column(name = "price")
    private BigDecimal price;

    @Column(name = "image_url")
    private String imageUrl;

    @Column(name = "active")
    private boolean active;

    @Column(name = "date_created")
    @CreationTimestamp
    private Date dateCreated;

    @Column(name = "last_updated")
    @UpdateTimestamp
    private Date lastUpdated;

    // getter and setter methods

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", sku='" + sku + '\'' +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", price=" + price +
                ", imageUrl='" + imageUrl + '\'' +
                ", active=" + active +
                ", dateCreated=" + dateCreated +
                ", lastUpdated=" + lastUpdated +
                '}';
    }
}

ProductRepository

Let's create ProductRepository which extends the JpaRepository interface:
import net.javaguides.springdatajpacourse.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {

}

Configure MySQL and Hibernate Properties

Let's use the MySQL database to store and retrieve the data in this example and we gonna use Hibernate properties to create and drop tables.

Open the application.properties file and add the following configuration to it:

spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false
spring.datasource.username=root
spring.datasource.password=Mysql@123

spring.jpa.hibernate.ddl-auto = create-drop

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Make sure that you will create a demo database before running the Spring boot application.
Also, change the MySQL username and password as per your MySQL installation on your machine.

Testing findById() Method

Let's write a JUnit test to test findById() method:

import net.javaguides.springdatajpacourse.entity.Product;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import java.math.BigDecimal;
import java.util.List;

@DataJpaTest
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
class ProductRepositoryTest {

    @Autowired
    private ProductRepository productRepository;

    protected Product getProduct1(){
        Product product = new Product();
        product.setName("product 1");
        product.setDescription("product 1 desc");
        product.setPrice(new BigDecimal(100));
        product.setSku("product 1 sku");
        product.setActive(true);
        product.setImageUrl("product1.png");
        return product;
    }

    @Test
    void testFindByIdMethod(){
        Product product = getProduct1();

        // save product
        productRepository.save(product);

        // get product by id
        Product savedProduct = productRepository.findById(product.getId()).get();

        System.out.println(savedProduct.getName());
    }
}
We are using @DataJpaTest annotation to write a JUnit test ProductRepository findById() method.

@AutoConfigureTestDatabase annotation is to disable embedded in-memory database support.

Related Spring Data JPA Examples


Comments