Spring Data JPA - findById() Method Example

In this source code example, we will demonstrate how to use the findById() method in Spring Data JPA to fetch or retrieve an entity by id from the database.

As the name depicts, the findById() method allows us to get or retrieve an entity based on a given id (primary key) from the DB. 

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:



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 javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;

public class Product {

    @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")
    private Date dateCreated;

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

    // getter and setter methods

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


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.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

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

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;

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

    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");
        return product;

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

        // save product

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

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

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course