Spring Boot & JPA - Application Setup



As in previous chapter Environment Setup, we've imported the generated spring boot project in eclipse. Now let's create the following structure in src/main/java folder.

Project Structure
  • com.tutorialspoint.controller.EmployeeController − A REST Based Controller to implement REST based APIs.

  • com.tutorialspoint.entity.Employee − An entity class representing the corresponding table in database.

  • com.tutorialspoint.repository.EmployeeRepository − A Repository Interface to implement the CRUD operations on the database.

  • com.tutorialspoint.service.EmployeeService − A Service Class to implement the business opearations over repository functions.

  • com.tutorialspoint.springbooth2.SprintBootH2Application − A Spring Boot Application class.

Example - JPA Based Spring Boot Application

SprintBootH2Application class is already present. We need to create the above packages and relevant classes and interface as shown below −

Entity - Entity.java

Following is the default code of Employee. It represents a Employee table with id, name, age and email columns.

package com.tutorialspoint.entity;

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

@Entity
@Table
public class Employee {

   // database column mappings
   @Id
   @Column
   private int id;

   @Column
   private String name;

   @Column
   private int age;

   @Column
   private String email;

   // setter/getter methods
   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 int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }

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

Repository - EmployeeRepository.java

Following is the default code of Repository to implement CRUD operations on above entity, Employee.

package com.tutorialspoint.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.tutorialspoint.entity.Employee;

@Repository
public interface EmployeeRepository extends CrudRepository<Employee, Integer>  {
}

Service - EmployeeService.java

Following is the default code of Service to implement operations over repository functions.

package com.tutorialspoint.service;

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

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

import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.repository.EmployeeRepository;

@Service
public class EmployeeService {
   
   @Autowired
   EmployeeRepository repository;
   
   // get an employee by id
   public Employee getEmployeeById(int id) {
      return repository.findById(id).get();
   }
   
   // get all employees
   public List<Employee> getAllEmployees(){
      List<Employee> employees = new ArrayList<Employee>();
      repository.findAll().forEach(employee -> employees.add(employee));
      return employees;
   }
   
   // create or update an employee
   public void saveOrUpdate(Employee employee) {
      repository.save(employee);
   }
   
   // delete an employee by id
   public void deleteEmployeeById(int id) {
      repository.deleteById(id);
   }
}

Controller - EmployeeController.java

Following is the default code of Controller to implement REST APIs.

package com.tutorialspoint.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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.service.EmployeeService;

@RestController
@RequestMapping(path = "/emp")
public class EmployeeController {

   @Autowired
   EmployeeService employeeService;

   // get all employees
   @GetMapping("/employees")
   public List<Employee> getAllEmployees(){
      return employeeService.getAllEmployees();
   }

   // get an employee by id
   @GetMapping("/employee/{id}")
   public Employee getEmployee(@PathVariable("id") int id) {
      return employeeService.getEmployeeById(id);
   }

   // delete an employee by id
   @DeleteMapping("/employee/{id}")
   public void deleteEmployee(@PathVariable("id") int id) {
      employeeService.deleteEmployeeById(id);
   }

   // create an employee
   @PostMapping("/employee")
   public void addEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);   
   }

   // update an employee
   @PutMapping("/employee")
   public void updateEmployee(@RequestBody Employee employee) {
      employeeService.saveOrUpdate(employee);
   }	
}

Application - SprintBootH2Application.java

Following is the updated code of Application to use above classes.

package com.tutorialspoint.sprintbooth2;

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.tutorialspoint.controller","com.tutorialspoint.service"})
@EntityScan("com.tutorialspoint.entity")
@EnableJpaRepositories("com.tutorialspoint.repository")
@SpringBootApplication
public class SprintBootH2Application {
   public static void main(String[] args) {
      SpringApplication.run(SprintBootH2Application.class, args);
   }
}

Output

Create following maven configuration in eclipse to run the springboot application with goal spring-boot:run. This configuration will help to run the REST APIs and we can test them using POSTMAN.

Maven Configuration

Run the application

In eclipse, run the Employee Application configuration. Eclipse console will show the similar output.

[INFO] Scanning for projects...
[INFO] 
[INFO] [1m------------------< [0;36mcom.tutorialspoint:springboot-h2[0;1m >------------------[m
[INFO] [1mBuilding springboot-h2 0.0.1-SNAPSHOT[m
[INFO]   from pom.xml
[INFO] [1m--------------------------------[ jar ]---------------------------------[m
...

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.5.6)

2025-10-02T13:38:39.329+05:30  INFO 47300 --- [springboot-h2] [  restartedMain] c.t.s.SpringbootH2Application            : Starting SpringbootH2Application using Java 21.0.6 with PID 47300 (D:\Projects\springboot-h2\target\classes started by mahes in D:\Projects\springboot-h2)
...
2025-10-02T13:38:41.731+05:30  INFO 47300 --- [springboot-h2] [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2025-10-02T13:38:41.949+05:30  WARN 47300 --- [springboot-h2] [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2025-10-02T13:38:42.238+05:30  INFO 47300 --- [springboot-h2] [  restartedMain] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
2025-10-02T13:38:42.313+05:30  INFO 47300 --- [springboot-h2] [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2025-10-02T13:38:42.353+05:30  INFO 47300 --- [springboot-h2] [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2025-10-02T13:38:42.361+05:30  INFO 47300 --- [springboot-h2] [  restartedMain] c.t.s.SpringbootH2Application            : Started SpringbootH2Application in 3.359 seconds (process running for 3.69)

Once server is up and running, Use Postman to make a POST request to add a record first.

Set the following parameters in POSTMAN.

  • HTTP Method - POST

  • URL - http://localhost:8080/emp/employee

  • BODY - An employee JSON

{  
   "id": "1",  
   "age": "35",  
   "name": "Julie",  
   "email": "julie@gmail.com"  
}   

Click on Send Button and check the response status to be OK.

Add Employee

Now make a GET Request to get all records.

Set the following parameters in POSTMAN.

  • HTTP Method - GET

  • URL - http://localhost:8080/emp/employees

Click the send button and verify the response.

Get All Employees
Advertisements