Spring Data JPA Projections: A Step-by-Step Tutorial

Spring Data JPA projections allow you to select specific fields from an entity instead of fetching the whole entity. This can help reduce the amount of data transferred from the database to your application, improving performance. In this tutorial, we will explore how to use Spring Data JPA projections in a Spring Boot 3.2 application with a Student entity.

Prerequisites

  • JDK 17 or later
  • Maven or Gradle
  • IDE (IntelliJ IDEA, Eclipse, etc.)

Step 1: Set Up a Spring Boot Project

1.1 Create a New Spring Boot Project

Use Spring Initializr to create a new project with the following dependencies:

  • Spring Web
  • Spring Data JPA
  • H2 Database

Download and unzip the project, then open it in your IDE.

1.2 Configure application.properties

Set up the application properties for your project to connect to the H2 database. This file is located in the src/main/resources directory.

# src/main/resources/application.properties

# H2 Database configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.platform=h2

# JPA configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

# H2 Console configuration
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

Explanation:

  • Configures the connection to the H2 in-memory database.
  • Enables SQL logging.
  • Sets up JPA to update the database schema automatically.
  • Enables the H2 console for easy database management.

Step 2: Define the Entity Class

2.1 Create the Student Entity

Create an entity class to represent a student in the database.

package com.example.demo.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    private int age;

    // Getters and setters
    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Explanation:

  • @Entity: Specifies that the class is an entity and is mapped to a database table.
  • @Id and @GeneratedValue: Indicates the primary key and its generation strategy.

Step 3: Define Projection Interfaces

3.1 Create Projection Interfaces

Define projection interfaces to fetch specific fields from the Student entity.

package com.example.demo.projection;

public interface StudentNameProjection {
    String getName();
}

public interface StudentEmailProjection {
    String getEmail();
}

Explanation:

  • StudentNameProjection: Interface to fetch only the name field.
  • StudentEmailProjection: Interface to fetch only the email field.

Step 4: Create the Repository Interface

4.1 Create the StudentRepository

Create a repository interface to perform CRUD operations on the Student entity and use projections.

package com.example.demo.repository;

import com.example.demo.entity.Student;
import com.example.demo.projection.StudentEmailProjection;
import com.example.demo.projection.StudentNameProjection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

    @Query("SELECT s.name AS name FROM Student s")
    List<StudentNameProjection> findAllStudentNames();

    @Query("SELECT s.email AS email FROM Student s")
    List<StudentEmailProjection> findAllStudentEmails();
}

Explanation:

  • @Repository: Indicates that the interface is a Spring Data repository.
  • JpaRepository<Student, Long>: Provides CRUD operations for the Student entity.
  • findAllStudentNames: Uses a projection to fetch only the names of all students.
  • findAllStudentEmails: Uses a projection to fetch only the emails of all students.

Step 5: Create Service and Controller Layers

5.1 Create the StudentService

Create a service class to handle business logic related to students and projections.

package com.example.demo.service;

import com.example.demo.projection.StudentEmailProjection;
import com.example.demo.projection.StudentNameProjection;
import com.example.demo.entity.Student;
import com.example.demo.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentService {

    @Autowired
    private StudentRepository studentRepository;

    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    public Optional<Student> getStudentById(Long id) {
        return studentRepository.findById(id);
    }

    public Student createStudent(Student student) {
        return studentRepository.save(student);
    }

    public void deleteStudent(Long id) {
        studentRepository.deleteById(id);
    }

    public List<StudentNameProjection> getAllStudentNames() {
        return studentRepository.findAllStudentNames();
    }

    public List<StudentEmailProjection> getAllStudentEmails() {
        return studentRepository.findAllStudentEmails();
    }
}

Explanation:

  • getAllStudentNames(): Retrieves all student names using the StudentNameProjection.
  • getAllStudentEmails(): Retrieves all student emails using the StudentEmailProjection.

5.2 Create the StudentController

Create a REST controller to expose endpoints for interacting with students and using projections.

package com.example.demo.controller;

import com.example.demo.projection.StudentEmailProjection;
import com.example.demo.projection.StudentNameProjection;
import com.example.demo.entity.Student;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping
    public List<Student> getAllStudents() {
        return studentService.getAllStudents();
    }

    @GetMapping("/{id}")
    public Optional<Student> getStudentById(@PathVariable Long id) {
        return studentService.getStudentById(id);
    }

    @PostMapping
    public Student createStudent(@RequestBody Student student) {
        return studentService.createStudent(student);
    }

    @DeleteMapping("/{id}")
    public void deleteStudent(@PathVariable Long id) {
        studentService.deleteStudent(id);
    }

    @GetMapping("/names")
    public List<StudentNameProjection> getAllStudentNames() {
        return studentService.getAllStudentNames();
    }

    @GetMapping("/emails")
    public List<StudentEmailProjection> getAllStudentEmails() {
        return studentService.getAllStudentEmails();
    }
}

Explanation:

  • @GetMapping("/names"): Maps the endpoint to retrieve all student names.
  • @GetMapping("/emails"): Maps the endpoint to retrieve all student emails.

Step 6: Running and Testing the Application

6.1 Run the Application

Run the Spring Boot application using your IDE or the command line:

./mvnw spring-boot:run

6.2 Access the H2 Console

You can access the H2 console to inspect the database contents at http://localhost:8080/h2-console. Use the following JDBC URL to connect:

  • JDBC URL: jdbc:h2:mem:testdb
  • Username: sa
  • Password: password

6.3 Test the Endpoints

Use a tool like Postman or your browser to test the endpoints.

Create a Student

  • URL: http://localhost:8080/students
  • Method: POST
  • Body:
    {
        "name": "John Doe",
        "email": "john.doe@example.com",
        "age": 20
    }
    

Get All Students

  • URL: http://localhost:8080/students
  • Method: GET

Get a Student by ID

  • URL: http://localhost:8080/students/{id}
  • Method: GET

Delete a Student

  • URL: http://localhost:8080/students/{id}
  • Method: DELETE

Get All Student Names

  • URL: http://localhost:8080/students/names
  • Method: GET

Get All Student Emails

  • URL: http://localhost:8080/students/emails
  • Method: GET

Conclusion

In this tutorial, you have learned how to use Spring Data JPA projections in a Spring Boot 3.2 application. We covered:

  • Setting up a Spring Boot project with Spring Data JPA and H2.
  • Defining an entity class and repository.
  • Creating projection interfaces.
  • Using projections in the service and controller layers.
  • Running and testing the application using REST endpoints.

By following these steps, you can effectively use projections to optimize data retrieval in your Spring Boot applications using Spring Data JPA.


Comments