Building a Robust REST API With Spring Boot, H2 Database
Building a Robust REST API With Spring Boot, H2 Database
Introduction
In this blog, we'll build a REST API using Spring Boot, the H2 in-memory database, and Spring
Data JPA. We’ll also cover how to handle exceptions gracefully and test our API with Postman.
Let’s dive in!
1. Project Structure
src
├── main
│ ├── java
│ │ └── com
│ │ └── telusko
│ │ ├── controller
│ │ │ └── StudentController.java
│ │ ├── dao
│ │ │ └── StudentRepository.java
│ │ ├── entity
│ │ │ └── Student.java
│ │ ├── exception
│ │ │ ├── GlobalExceptionHandler.java
│ │ │ ├── StudentNotFoundException.java
│ │ │ └── ErrorResponse.java
│ │ └── service
│ │ └── StudentService.java
│ └── resources
│ ├── application.properties
│ └── static
│ └── templates
└── test
└── java
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. H2 Database Configuration
File: application.properties
spring.application.name=h2-database-1
# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.sql.init.platform=h2
server.port=9999
File: Student.java
package com.telusko.entity;
import jakarta.persistence.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
@Entity
@Table(name = "StudentTable")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
"student_seq")
@SequenceGenerator(name = "student_seq", sequenceName =
"student_sequence", allocationSize = 1, initialValue = 2115800000)
private int id;
@Transient
private String dob; // Not persisted in the database
}
Explanation of Annotations:
File: StudentRepository.java
package com.telusko.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.telusko.entity.Student;
Explanation:
File: StudentService.java
package com.telusko.service;
import com.telusko.dao.StudentRepository;
import com.telusko.entity.Student;
import com.telusko.exception.StudentNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
Explanation:
File: StudentController.java
package com.telusko.controller;
import com.telusko.entity.Student;
import com.telusko.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService studentService;
Explanation:
8. Exception Handling
File: StudentNotFoundException.java
package com.telusko.exception;
File: GlobalExceptionHandler.java
package com.telusko.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(StudentNotFoundException.class)
public ResponseEntity<ErrorResponse>
handleStudentNotFoundException(StudentNotFoundException ex) {
ErrorResponse errorResponse = new ErrorResponse(ex.getMessage(),
HttpStatus.NOT_FOUND.value());
return
ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception
ex) {
ErrorResponse errorResponse = new ErrorResponse("An unexpected
error occurred: " + ex.getMessage(),
HttpStatus.INTERNAL_SERVER_ERROR.value());
return
ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse)
;
}
}
File: ErrorResponse.java
package com.telusko.exception;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ErrorResponse {
private String message;
private int status;
}
Explanation:
1. Download Postman:
○ Go to the Postman website and download the application for your operating
system.
○ Install and open Postman.
2. Start Your Spring Boot Application:
○ Ensure your Spring Boot application is running. You should see console output
indicating that the server is started, usually at http://localhost:9999.
{
"name": "Shiva Srivastava",
"email": "shiva@gmail.com",
"dob": "2002-11-13"
}
{
"name": "Shiva Srivastava",
"email": "shivasrivastava@gmail.com",
"dob": "2002-11-13"
}
Conclusion
In this blog, we explored how to build a REST API using Spring Boot, H2 Database, and Spring
Data JPA. We handled exceptions gracefully and tested our API with Postman. This robust
architecture will help you efficiently manage student data and improve your skills with Spring
Boot.