Spring Boot JPA Examples

Spring Boot JPA with Examples

In this article, I am going to discuss Spring Boot JPA with Examples. Please read our previous article where we discussed Introduction to Spring Boot JPA.

Spring Boot JPA Examples

In our previous chapter, we learned the theory of JPA (Java Persistence API). Let us learn how to implement it. We will use Apache Derby, an open-source in-memory database coded in Java. Apace Derby has the following advantages:

  • Easy to install, deploy and use.
  • It is based on Java, JDBC, and SQL standards.
  • Provides an embedded JDBC driver that allows us to embed Derby in any Java program.
  • Supports client/server mode with the Derby Network Client JDBC driver and Derby Network Server.

Step 1: Create a new project using Spring Initializr in VS Code. Include the following dependencies:

  • Spring Web
  • Spring Data JPA
  • H2 Database

Spring Boot JPA Examples

Ensure that the dependencies are installed:

Spring Boot JPA Examples

Step 2: Create a directory with the path as src/main/java/com/dotnet/entity.

Step 3: Create a POJO class called Student.java in the newly created src/main/java/com/dotnet/entity directory.

Step 4: Add the following lines to the file:

Spring Boot JPA Examples

This code implies the following:

  • The @Entity annotation for the class marks that the class can be stored as an entity in a database.
  • The @Table annotation signifies that the class can be stored as a table.
  • The @Id annotation for the id variable indicates that the id variable can be used as the primary key in the database.
  • Two more fields, name and email have been added. These fields will also be stored in the database.
  • Each field is given the @Column annotation. This means that each field should be made into its own column.

Step 5: Add the setters and getters.

If you are using VS Code, there is a shortcut to do this. Right-click anywhere within the VS Code text editor to see the following menu:

Spring Boot JPA Examples

Click on the “Source Action…” option. This opens the following dropdown menu:

Spring Boot JPA Examples

Upon clicking on the “Generate Getters and Setters…” button, the following menu opens:

Spring Boot JPA with Examples

Select all three fields and click on OK. The getters and setters shall be auto-generated:

Spring Boot JPA with Examples

Step 6: Add constructors. Using the same “Source Actions…” option, add constructors to the POJO class:

Spring Boot JPA with Examples

Click on OK:

Spring Boot JPA with Examples

This generates the default constructor:

Spring Boot JPA with Examples

Step 7: Create a directory with its path as src/main/java/com/dotnet/repository.

Step 8: Create a class called StudentRepository.java in the newly created src/main/java/com/dotnet/repository directory.

Step 9: Modify the newly created StudentRepository.java as follows:

Spring Boot JPA with Examples

We have done the following changes:

  • Imported required packages
  • Added @Repository annotation to the class, to indicate that it is a repository.
  • Made the class into an interface
  • Extended the CrudRepository interface.

Step 10: Create a directory with its path as src/main/java/com/dotnet/service.

Step 11: Create a class called StudentService.java in the newly created src/main/java/com/dotnet/service directory.

Step 12: Modify the newly created StudentRepository.java as follows:

Spring Boot JPA with Examples

We have done the following changes:

  • Imported required packages
  • Added the @Service annotation to the class, to indicate that it is a service class.
  • Added function to retrieve, add, delete, and modify students. Note that the addStudent() function can also be used to update students. This fulfills the CRUD (Create, Retrieve, Update, Delete) paradigm.

Step 13: Create a directory with its path as src/main/java/com/dotnet/controller.

Step 14: Create a class called StudentController.java in the newly created src/main/java/com/dotnet/ controller directory.

Step 15: Import the following packages into the class:

Spring Boot JPA with Examples

Step 16: Modify the newly created StudentController.java as follows:

Spring Boot JPA with Examples

We have done the following changes:

  • Added the @RestController annotation to the class. This marks the class as a REST controller.
  • Added functions for CRUD and mapped them to URLs.

This makes it such that when a client accesses a particular URL, their request shall be forwarded to this controller. The controller reviews the type of request and then forwards it to the correct function.

Step 17: Compile and execute the application. Ensure compilation is successful:

Spring Boot JPA with Examples

Step 18: Open Postman and send a GET request to http://localhost:8080/students. This should return an empty value because no data has been added to the database yet.

Spring Boot JPA with Examples

Step 19: Open Postman and send a POST request to http://localhost:8080/add-student. This will not return any reply. However, the status code shall be shown as 200 OK.

Spring Boot JPA with Examples

Step 20: Open Postman and send a GET request to http://localhost:8080/students. This displays the newly-added student:

Spring Boot JPA with Examples

Step 21: Add a few more students using multiple POST requests. In my case, I have added three more students:

Spring Boot JPA with Examples

Step 22: Update one of the students using a PUT request:

Spring Boot JPA with Examples

Check that the update is successful using a GET request:

Spring Boot JPA with Examples

Step 23: Delete one of the students using a DELETE request:

Spring Boot JPA with Examples

Check that the delete operation is successful using a GET request:

Spring Boot JPA with Examples

Congratulations! You now know how to develop an application in Spring Boot using JPA.

The Complete Example Code
/src/main/java/com/dotnet/controller/StudentController.java
package com.dotnet.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.dotnet.entity.Student;
import com.dotnet.service.StudentService;

@RestController
public class StudentController
{
    @Autowired
    private StudentService studentService;
    
    @GetMapping(value = "/students")
    public List<Student> getAllStudents()  
    {
        return studentService.getAllStudents();
    }

    @GetMapping(value = "/students/{id}")
    public Student getStudentById(@PathVariable("id") int id)  
    {
        return studentService.getStudentById(id);
    }

    @DeleteMapping(value = "/students/{id}")
    public void deleteStudentById (@PathVariable("id") int id)
    {
        studentService.deleteStudentById(id);
    }

    @PostMapping(value = "/add-student")
    public void addStudent (@RequestBody Student student)
    {
        studentService.addStudent(student);
    }

    @PutMapping(value = "/add-student")
    public void updateStudent (@RequestBody Student student)
    {
        studentService.addStudent(student);
    }
}
/src/main/java/com/dotnet/entity/Student.java
package com.dotnet.entity;

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

@Entity
@Table
public class Student
{
    @Id
    @Column
    private int id;

    @Column
    private String name;

    @Column
    private String email;

    public int getId()                  {return id;}
    public void setId(int 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 Student() {
    }
}
/src/main/java/com/dotnet/jpa/JpaApplication.java
package com.dotnet.jpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@ComponentScan({"com.dotnet.controller","com.dotnet.service"})
@EntityScan("com.dotnet.entity")
@EnableJpaRepositories("com.dotnet.repository")
@SpringBootApplication
public class JpaApplication {

    public static void main(String[] args) {
        SpringApplication.run(JpaApplication.class, args);
    }
}
/src/main/java/com/dotnet/repository/StudentRepository.java
package com.dotnet.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import com.dotnet.entity.Student;

@Repository
public interface StudentRepository extends CrudRepository<Student, Integer>
{
    
}
/src/main/java/com/dotnet/service/StudentService.java
package com.dotnet.service;

import java.util.List;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dotnet.entity.Student;
import com.dotnet.repository.StudentRepository;

@Service
public class StudentService
{
    @Autowired
    private StudentRepository studentRepository;

    public Student getStudentById (int id)
    {
        return studentRepository.findById(id).get();
    }

    public List<Student> getAllStudents()
    {
        List<Student> studentList = new ArrayList<>();
        studentRepository.findAll().forEach(student -> studentList.add(student));
        return studentList;
    }

    public void addStudent(Student studentRecord)
    {
        studentRepository.save(studentRecord);    
    }

    public void deleteStudentById (int id)
    {
        studentRepository.deleteById(id);
    }
}

In the next article, I am going to discuss Spring Boot JDBC with Examples. Here, in this article, I try to explain Spring Boot JPA Examples. I hope you enjoy this Spring Boot JPA with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *