In the previous tutorial we have seen, how we can insert data to the H2 database. In this tutorial we will see, how we can read data from the database.
Below are the preliminary steps, we will follow :
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>springbootproject</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.1</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> </project>
@Entity
public class Student {
@Id
int roll;
String name;
int age;
int className;
}
@RestController
public class HelloWorldController {
@Autowired
StudentService studentService;
@RequestMapping(method = RequestMethod.POST, value = "/students")
public void insertStudent(@RequestBody Student student) {
studentService.insertStudentDetails(student);
}
@RequestMapping(method = RequestMethod.GET, value = "/students")
public List readStudent() {
return studentService.readStudentDetails();
}
} 
@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;
public void insertStudentDetails(Student student) {
studentRepository.save(student);
}
public List readStudentDetails() {
List studentList = (List) studentRepository.findAll();
return studentList;
}
} 
public ListreadStudentDetails() { List studentList = (List ) studentRepository.findAll(); return studentList; }
ListstudentList = (List ) studentRepository.findAll();
public interface StudentRepository extends CrudRepository<Student, Integer> {
}
Now, that we are done with the coding (In Spring Boot). Let us start Spring Boot application.
Then open Postman and try adding the details of John,
{"name": "John", "roll": 1, "age": 8, "className": 5}To the endpoint
localhost:8080/students
Using the method as POST

And once the details of John is added. Let us try to retrieve the details of John from the H2 database.
To retrieve the details of John from the H2 database, let us change the method to GET and hit the same endpoint (i.e. localhost:8080/students).
And we are able to retrieve the details of John from the database.
