Spring Data JDBC

Working with Java JDBC Technology

In the enterprise applications, if we use JDBC technology to perform Database operations then we have to use the following steps.

  1. Load and Register Driver
  2. Establish Connection between Java application and database
  3. Create ether statement or PreparedStatement or CallableStatement
  4. Write and Execute SQL queries
  5. Close the resources.

In the above steps , steps 1,2,3 and 5 are very much common in all the Jdbc applications, it is boilerplate code, it is not suggestible in the enterprise applications.

Spring JDBC Template

To avoid the above boilerplate code in the enterprise applications Spring framework has provided a JDBC module.

If we want to perform database operations by using Spring JDBC then we have to use the following steps.

  1. Create a Spring project with all the dependencies.
  2. Create a POJO Class which is like a model class
  3. Create a DAO interface and its implementation class.
  4. Declare JdbcTemplate property and its setter method (through auto-wiring).
  5. Perform all the Database operations in DAO class.
  6. We can create a Service interface and Service implementation classes. Auto-wire DAO into the Service implementation class.
  7. Create a Controller class that auto-wires Service.
  8. Provide the following configurations in the Spring Configuration file.
    • Datasource Configurations
    • JdbcTemplate configuration
    • Dao Configuration
  9. In Main class, in main() method , using controller we can access DAO and perform operations with the database.

EX:

Employee.java — POJO class

package com.durgasoft.app17.beans;

public class Employee {

private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {
return eno;
}

public void setEno(int eno) {
this.eno = eno;
}

public String getEname() {
return ename;
}

public void setEname(String ename) {
this.ename = ename;
}

public float getEsal() {
return esal;
}

public void setEsal(float esal) {
this.esal = esal;
}

public String getEaddr() {
return eaddr;
}

public void setEaddr(String eaddr) {
this.eaddr = eaddr;
}

@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
", eaddr='" + eaddr + '\'' +
'}'+"\n";
}
}

EmployeeDao.java — DAO Interface

package com.durgasoft.app17.dao;

import com.durgasoft.app17.beans.Employee;
import java.util.List;

public interface EmployeeDao {
public String add(Employee employee);
public Employee search(int eno);
public String update(Employee employee);
public String delete(int eno);
public List<Employee> getAllEmployees();
}

EmployeeDaoImpl.java — DAO Implementation class

package com.durgasoft.app17.dao;

import com.durgasoft.app17.beans.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public class EmployeeDaoImpl implements EmployeeDao {

@Autowired
private JdbcTemplate jdbcTemplate;


@Override
public String add(Employee employee) {
String status = "";
try{
Employee emp = search(employee.getEno());
if(emp != null){
status = "EMPLOYEE ALREADY EXISTS";
}else{
int rowCount = jdbcTemplate.update("insert into emp1 values(?,?,?,?)",
new Object[]{
employee.getEno(),
employee.getEname(),
employee.getEsal(),
employee.getEaddr()
}
);
if(rowCount == 1){
status = "EMPLOYEE ADDED SUCCESSFULLY";
}else{
status = "EMPLOYEE INSERTION FAILED";
}
}
} catch (Exception e) {
e.printStackTrace();
}
return status;
}

@Override
public Employee search(int eno) {
List<Employee> employees = jdbcTemplate.query("select * from emp1 where eno = "+eno,
(rs, rowNo)-> {
Employee employee1 = new Employee();
employee1.setEno(rs.getInt("ENO"));
employee1.setEname(rs.getString("ENAME"));
employee1.setEsal(rs.getFloat("ESAL"));
employee1.setEaddr(rs.getString("EADDR"));
return employee1;
});
return employees.size() > 0 ? employees.get(0) : null;
}

@Override
public String update(Employee employee) {
String status = "";
Employee emp = search(employee.getEno());
if(emp != null) {

int rowCount = jdbcTemplate.update("update emp1 set ENAME = ?, ESAL = ?, EADDR = ? where ENO = ?",
new Object[]{
employee.getEname(),
employee.getEsal(),
employee.getEaddr(),
employee.getEno()
});
if (rowCount == 1) {
status = "EMPLOYEE UPDATED SUCCESSFULLY";
} else {
status = "EMPLOYEE UPDATING FAILED";
}
}else{
status = "EMPLOYEE NOT FOUND";
}
return status;
}

@Override
public String delete(int eno) {
String status = "";
Employee emp = search(eno);
if(emp != null) {
int rowCount = jdbcTemplate.update("delete from emp1 where ENO = " + eno);
if (rowCount == 1) {
status = "EMPLOYEE DELETED SUCCESSFULLY";
} else {
status = "EMPLOYEE DELETION FAILED";
}
}else{
status = "EMPLOYEE NOT FOUND";
}
return status;
}

@Override
public List<Employee> getAllEmployees() {
List<Employee> employees = jdbcTemplate.query("select * from emp1",
(rs, rowNo)-> {
Employee employee1 = new Employee();
employee1.setEno(rs.getInt("ENO"));
employee1.setEname(rs.getString("ENAME"));
employee1.setEsal(rs.getFloat("ESAL"));
employee1.setEaddr(rs.getString("EADDR"));
return employee1;
});
return employees;
}
}

EmployeeService.java — Service class — this is wrapper over DAO

package com.durgasoft.app17.service;

import com.durgasoft.app17.beans.Employee;
import java.util.List;

public interface EmployeeService {
public String addEmployee(Employee employee);
public Employee searchEmployee(int eno);
public String updateEmployee(Employee employee);
public String deleteEmployee(int eno);
public List<Employee> getAllEmployees();
}

EmployeeServiceImpl.java — Service implementation class

package com.durgasoft.app17.service;

import com.durgasoft.app17.beans.Employee;
import com.durgasoft.app17.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeDao employeeDao;

@Override
public String addEmployee(Employee employee) {
String status = employeeDao.add(employee);
return status;
}

@Override
public Employee searchEmployee(int eno) {
Employee employee = employeeDao.search(eno);
return employee;
}

@Override
public String updateEmployee(Employee employee) {
String status = employeeDao.update(employee);
return status;
}

@Override
public String deleteEmployee(int eno) {
String status = employeeDao.delete(eno);
return status;
}

@Override
public List<Employee> getAllEmployees() {
List<Employee> employees = employeeDao.getAllEmployees();
return employees;
}
}

EmployeeCOntroller.java — Controller class

package com.durgasoft.app17.controller;

import com.durgasoft.app17.beans.Employee;
import com.durgasoft.app17.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.util.List;

@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;


public String addEmployee(Employee employee) {
String status = employeeService.addEmployee(employee);
return status;
}

public Employee searchEmployee(int eno) {
Employee employee = employeeService.searchEmployee(eno);
return employee;
}

public String updateEmployee(Employee employee) {
String status = employeeService.updateEmployee(employee);
return status;
}

public String deleteEmployee(int eno) {
String status = employeeService.deleteEmployee(eno);
return status;
}

public List<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
}

AppRunner.java

package com.durgasoft.app17.runner;

import com.durgasoft.app17.beans.Employee;
import com.durgasoft.app17.controller.EmployeeController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class AppRunner implements CommandLineRunner {

@Autowired
private EmployeeController employeeController;

@Override
public void run(String... args) throws Exception {
/*Employee employee = new Employee();
employee.setEno(111);
employee.setEname("Durga");
employee.setEsal(50000);
employee.setEaddr("Hyd");
String status = employeeController.addEmployee(employee);
System.out.println(status);*/

/*Employee employee = employeeController.searchEmployee(222);
if(employee == null) {
System.out.println("Employee not found");
}else{
System.out.println("Employee Details");
System.out.println("-------------------------");
System.out.println("Employee Number : "+employee.getEno());
System.out.println("Employee Name : "+employee.getEname());
System.out.println("Employee Salary : "+employee.getEsal());
System.out.println("Employee Address : "+employee.getEaddr());
}*/

/*Employee employee = new Employee();
employee.setEno(555);
employee.setEname("Anil");
employee.setEsal(60000);
employee.setEaddr("Chennai");
String status = employeeController.updateEmployee(employee);
System.out.println(status);*/

/*String status = employeeController.deleteEmployee(111);
System.out.println(status);*/

List<Employee> employees = employeeController.getAllEmployees();
System.out.println(employees);
}
}

application.properties — Spring configurations to specify database properties

spring.application.name=app17
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=Nagoor@786

Adding required dependencies to the Spring project — pom.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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.durgasoft</groupId>
<artifactId>app17</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app17</name>
<description>app17</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

In the above Spring Application, we have to prepare a DAO class and we have to provide implementation for all the DAO methods like add(), search(), update(), delete(),….. as per the requirement.


Spring Boot Data JDBC

In Spring Boot Data JDBC, no need to provide implementation for all the DAO methods.

Spring Boot data JDBC has provided all the Dao methods implementations in the form of a predefined interface with the default methods that is CRUDRepository.

In Spring Boot, CRUDRepository interface has provided the following methods to perform the database operations.

save(): To save an Entity in the Database.
delete(): To delete an entity from the Database.
findById(): To find an entity on the basis of the Id value.
findAll(): To find all the entities from the Database
——
—–

In Spring Boot Data JDBC , it is not required to take a DAO class and it is not required to provide implementation to all the methods of the DAO interface, because CRUDRepositiry interface has provided all the methods as predefined methods , just we have to reuse these methods by extending Dao/Repository interface from CRUDRepository.

public interface EmployeeRepository extends CrudRepository {
—---All methods of CrudRepository are available here—---
}

Steps to use Spring Data JDBC

In Spring Boot, to prepare Data Jdbc applications then we have to use the following steps.

  • Prepare Spring Boot Project with the following dependencies.
    • Spring Web
    • Spring data jdbc
    • Mysql connector

CrudRepository

CrudRepository is a part of the Spring Data JPA framework, which provides convenient methods for performing CRUD (Create, Read, Update, Delete) operations on entities in a relational database. CrudRepository is an interface that extends the basic Repository interface and adds generic CRUD methods to it. It is defined in the package org.springframework.data.repository and It extends the Spring Data Repository interface. If someone wants to use CrudRepository in the spring boot application he/she has to create an interface and extend the CrudRepository interface.

public interface CrudRepository<T, ID> extends Repository<T, ID>

Where:

  • T: Domain type that repository manages (Generally the Entity/Model class name)
  • ID: Type of the id of the entity that repository manages (Generally the wrapper class of your @Id that is created inside the Entity/Model class)
public interface DepartmentRepository extends CrudRepository<Department, Long> {}

https://www.geeksforgeeks.org/spring-boot-crudrepository-with-example

  • Create a table with auto_increment capability in Database:
sql> create table emp1(ENO int(5) primary key auto_increment, ENAME char(10), ESAL float(5), EADDR char(10));
sql>commit;
  • Prepare bean class or model class , it must be annotated with @Table and Id property must be annotated with @Id.
@Table(name=”emp1”)
public class Employee{
@Id
private int eno;
—-----
}
  • Create Repository interface by extending CrudRepository with the @Repository annotation.
@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer>{

}
  • Prepare Service class with @Service annotation and every method in Service class must be annotated with @Transactional annotation.
@Service
public class EmployeeServiceImpl implements EmployeeService {
@AutoWired
private EmployeeRepository employeeRepository;


@Transactional
public Employee addEmployee(Employee employee){
Employee emp = employeeRepository.save(employee);
return emp;
}
}
  • Prepare Controller class with @Controller annotation.
public class EmployeeController {
@AutoWired
private EmployeeService employeeService;

public void addEmployee(Employee employee){
employeeService.addEmployee(employee);
}
}
  • Prepare the runner class and Test the application.
@Component
public class AppRunner implements CommandLineRunner {
@Autowired
private EmployeeController employeeController;

public void run(String … args){
Employee emp = new Employee();
emp.setEno(111);
emp.setEname(“Durga”);
emp.setEsal(50000);
emp.setEaddr(“Hyd”);
employeeController.addEmployee(emp);
System.out.println(“Employee Added Successfully”);
}
}

In Spring Boot Data JDBC applications, it is not required to define DAO methods inside the repository classes, because CrudRepository interface has provided all the database operations in the form of predefined methods, still it is possible to define our own methods as per our own requirement with the following steps.

Example :

public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
@Modifying
@Query(“update….”)
public int update(-----);
}

public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
@Query(“select….”)
public int findByEaddr(-----);
}

Example using CrudRepository

Model class — this class maps to a table.

Employee.java

package com.durgasoft.app18.beans;

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;

@Table(name="emp5")
public class Employee {
@Id
private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {
return eno;
}

public void setEno(int eno) {
this.eno = eno;
}

public String getEname() {
return ename;
}

public void setEname(String ename) {
this.ename = ename;
}

public float getEsal() {
return esal;
}

public void setEsal(float esal) {
this.esal = esal;
}

public String getEaddr() {
return eaddr;
}

public void setEaddr(String eaddr) {
this.eaddr = eaddr;
}

@Override
public String toString() {
return "Employee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
", eaddr='" + eaddr + '\'' +
'}';
}
}

EmployeeRepository.java — class that Extends CrudRepository

package com.durgasoft.app18.repository;

import com.durgasoft.app18.beans.Employee;
import org.springframework.data.jdbc.repository.query.Modifying;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
//All Repository methods exist here to perform Database operation ,
// just access the methods from Service class
@Modifying
@Query("update emp5 set ENAME=:ename, ESAL=:esal, EADDR=:eaddr where ENO=:eno")
public Integer update(int eno, String ename, float esal, String eaddr);
}

Service class — EmployeeService.java

package com.durgasoft.app18.service;

import com.durgasoft.app18.beans.Employee;

public interface EmployeeService {
public Employee addEmployee(Employee employee);
public Employee searchEmployee(int eno);
public Iterable<Employee> getAllEmployees();
public Employee updateEmployee(Employee employee);
public int customUpdateEmployee(int eno, String ename, float esal, String eaddr);
public String deleteEmployee(int eno);
}

EmployeeServiceImpl.java

package com.durgasoft.app18.service;

import com.durgasoft.app18.beans.Employee;
import com.durgasoft.app18.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;

@Transactional
@Override
public Employee addEmployee(Employee employee) {
Employee emp = employeeRepository.save(employee);
return emp;
}

@Override
public Employee searchEmployee(int eno) {
Optional<Employee> optional = employeeRepository.findById(eno);
Employee emp = optional.get();
return emp;
}

@Override
public Iterable<Employee> getAllEmployees() {
Iterable<Employee> iterable = employeeRepository.findAll();
return iterable;
}

@Transactional
@Override
public Employee updateEmployee(Employee employee) {
Employee emp = employeeRepository.save(employee);
return emp;
}

//@Transactional
@Override
public int customUpdateEmployee(int eno, String ename, float esal, String eaddr) {
Integer val = employeeRepository.update(eno, ename, esal, eaddr);
return val;
}

@Transactional
@Override
public String deleteEmployee(int eno) {
employeeRepository.deleteById(eno);
return "Employee Deleted Successfully";
}
}

EmployeeController.java — Controller class that calls Service methods

package com.durgasoft.app18.controller;

import com.durgasoft.app18.beans.Employee;
import com.durgasoft.app18.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;

public Employee addEmployee(Employee employee) {
Employee emp = employeeService.addEmployee(employee);
return emp;
}
public Employee searchEmployee(int eno) {
Employee employee = employeeService.searchEmployee(eno);
return employee;
}
public Iterable<Employee> getAllEmployees() {
return employeeService.getAllEmployees();
}
public Employee updateEmployee(Employee employee) {
Employee emp = employeeService.updateEmployee(employee);
return emp;
}
public int customUpdateEmployee(Employee employee) {
int val = employeeService.customUpdateEmployee(
employee.getEno(),
employee.getEname(),
employee.getEsal(),
employee.getEaddr()
);
return val;
}
public String deleteEmployee(int eno) {
String status = employeeService.deleteEmployee(eno);
return status;
}
}

application.properties — to specify database parameters

spring.application.name=app18

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/durgadb
spring.datasource.username=root
spring.datasource.password=Nagoor@786

pom.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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.durgasoft</groupId>
<artifactId>app18</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>app18</name>
<description>app18</description>
<url/>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

PagingAndSortingRepository

The main purpose of PagingAndSortingRepository is to retrieve the data in the form of pages and to provide all the results in a particular order.

In Spring data JDBC applications, if we want to sort all the results there are able to use the following code.

Sort sort = Sort.by(Sort.Direction.fromString("ASC"), "saddr");
Iterable<Student> iterable = studentRepository.findAll(sort);

Where the “by()” method is able to define sorting direction like Ascending or Descending and the parameter on which we want to perform Sorting.

To get all the elements from Database with a particular Sorting order we have to use the following method.

public Iterable findAll(Sort sort)

In Spring Boot Data JDBC applications, if we want to read all the results page by page that is as per the pagination then we have to use the following Code.

PageRequest pageRequest = PageRequest.of(0,3);
Page<Student> page = studentRepository.findAll(pageRequest);
List<Student> stdList = page.stream().toList();

Where PageRequest is able to manage the page Number and the number of results in the respective page. To create a PageRequest object we will use the following method.

public static PageRequest Of(int pageNo, int numOfRecords)

Where Page object is able to manage the records which are retrieved  as per the PageRequest object provided page number and number of records.

To get a Page object we have to access the findAll() method from the Repository interface with the pageRequest parmeter.

If we want to get all Results from the Page object to the List we have to use the following code.

List<Student> stdList = page.stream().toList();

In Spring boot data JDBC, If we want to read all the results page by page as per the Pagination and as per a particular Sorting order then we have to use the following code.

PageRequest pageRequest = PageRequest.of(0,3, Sort.Direction.fromString("DESC"), "sname");
Page<Student> page = studentRepository.findAll(pageRequest);
List<Student> stdList = page.stream().toList();

Example using PagingAndSortingRepository

Repository class — StudentRepository.java

package com.durgasoft.app19.repository;

import com.durgasoft.app19.beans.Student;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends PagingAndSortingRepository <Student, String> {

}

Service class – StudentService.java

package com.durgasoft.app19.service;

import com.durgasoft.app19.beans.Student;
import java.util.List;

public interface StudentService {
public List<Student> getAllStudents();
}

Service implementation — StudentServiceImpl.java

package com.durgasoft.app19.service;

import com.durgasoft.app19.beans.Student;
import com.durgasoft.app19.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

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

@Service
public class StudentServiceImpl implements StudentService {

@Autowired
private StudentRepository studentRepository
;

@Override
public List<Student> getAllStudents() {
/*Sort sort = Sort.by(Sort.Direction.fromString("DESC"), "sname");
Iterable<Student> students = studentRepository.findAll(sort);
List<Student> studentList = (List<Student>) students;*/

/*PageRequest pageRequest = PageRequest.of(2, 2);
Page<Student> students = studentRepository.findAll(pageRequest);
List<Student> studentList = students.stream().toList();*/

PageRequest pageRequest = PageRequest.of(1, 2,
Sort.Direction.fromString("ASC"), "sname");
Page<Student> students = studentRepository.findAll(pageRequest);
List<Student> studentList = students.stream().toList();
return studentList;
}
}

Controller class — StudentController.java

package com.durgasoft.app19.controller;

import com.durgasoft.app19.beans.Student;
import com.durgasoft.app19.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.util.List;

@Controller
public class StduentController {

@Autowired
public StudentService studentService;


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

AppRunner.java

package com.durgasoft.app19.runner;

import com.durgasoft.app19.beans.Student;
import com.durgasoft.app19.controller.StduentController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class AppRunner implements CommandLineRunner {

@Autowired
private StduentController stduentController;

@Override
public void run(String... args) throws Exception {
List<Student> students = stduentController.getAllStudents();
System.out.println("SID\t\tSNAME\tSADDR");
System.out.println("---------------------------");
for (Student student : students) {
System.out.print(student.getSid()+"\t");
System.out.print(student.getSname()+"\t");
System.out.print(student.getSaddr()+"\n");
}
}
}

Spring Boot Application class

package com.durgasoft.app19;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App19Application {
public static void main(String[] args) {
SpringApplication.run(App19Application.class, args);
}
}