Complete tutorial of building Spring Boot REST API with Hibernate and Spring Data JPA.

Configuration
Java Compilation:
Java Runtime:
Maven:
Java Compilation:
Java Runtime:
Gradle:
JDK 17.0.2
JRE OpenJDK 17.0.2
Maven 3.9.6
JDK 17.0.2
JRE OpenJDK 17.0.2
Gradle 8.6
Create the following folder structure:
folder structure of Spring Boot REST API with Hibernate and Spring Data JPA
pom.xml: (if using Gradle, replace pom.xml with build.gradle)
<?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 http://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.2.2</version> <relativePath/> </parent> <groupId>org.example</groupId> <artifactId>SpringBootWebServiceSpringJpa</artifactId> <version>1.0</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web-services</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
plugins { id 'java' id 'org.springframework.boot' version '3.2.5' id 'io.spring.dependency-management' version '1.1.4' } group 'net.maxjava' version '1.0' repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.33' compileOnly 'org.projectlombok:lombok:1.18.30' annotationProcessor 'org.projectlombok:lombok:1.18.30' }
Some notes about pom.xml:
  • Use spring-boot-starter-parent as parent POM for Spring Boot application
  • Spring Boot 3.2.5 requires Java 17
  • Use spring-boot-starter-data-jpa for using Spring Data JPA
  • lombok is used to remove boilerplate code like get and set
  • Use spring-boot-maven-plugin to re-package all dependencies into a single, executable jar
  • By running mvn clean package, a jar artifact which is ready to run by using java -jar will be created
Some notes about gradle.build:
  • Use org.springframework.boot plugin for Spring Boot application, to make the jar executable and re-package all dependencies into a single jar
  • Spring Boot 3.2.5 requires Java 17
  • Use spring-boot-starter-data-jpa for using Spring Data JPA
  • Use io.spring.dependency-management plugin for dependency management
  • lombok is used to remove boilerplate code like get and set
  • By running gradle clean build, a jar artifact which is ready to run by using java -jar will be created
application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=myuser spring.datasource.password=mypassword spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Some notes about MySpringBootWebApplication.java:
  • Set up Spring datasource
  • Use PhysicalNamingStrategyStandardImpl for keeping converted physical names the same as logical names
MySpringBootWebApplication.java:
package maxjava; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MySpringBootWebApplication { public static void main(String[] args) { SpringApplication.run(MySpringBootWebApplication.class, args); } }
Some notes about MySpringBootWebApplication.java:
  • Mark a class with @SpringBootApplication and pass the class in SpringApplication.run will be good enough to run a Spring Boot application with web server (default setting)
  • We could just put SpringApplication.run inside the static main function and annotate the same class for simplicity
MyController.java:
package maxjava.controller; import maxjava.model.Customer; import maxjava.repository.CustomerEntity; import maxjava.repository.CustomerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Date; @RestController @RequestMapping("/myapp") public class MyController { @Autowired CustomerRepository customerRepository; @PostMapping("/customer") public void postCustomer(@RequestBody Customer customer) { CustomerEntity customerEntity = new CustomerEntity(); customerEntity.setName(customer.getName()); customerEntity.setEmail(customer.getEmail()); customerEntity.setCreatedDate(new Date()); customerRepository.save(customerEntity); } @GetMapping("/customer") public Customer getCustomer(@RequestParam("name") String name) { CustomerEntity customerEntity = customerRepository.findById(name).get(); Customer customer = new Customer(); customer.setName(customerEntity.getName()); customer.setEmail(customerEntity.getEmail()); return customer; } @PutMapping("/customer") public void putCustomer(@RequestBody Customer customer) { CustomerEntity customerEntity = new CustomerEntity(); customerEntity.setName(customer.getName()); customerEntity.setEmail(customer.getEmail()); customerEntity.setCreatedDate(new Date()); customerRepository.save(customerEntity); } @DeleteMapping("/customer") public void deleteCustomer(@RequestParam("name") String name) { customerRepository.deleteById(name); } }
Some notes about MyController.java:
  • Specifying @RestController will make this a controller to handle web request. Using @RestController instead of @Controller to perform serialization automatically, without the need of using @ResponseBody
  • This provides some basic CRUD APIs
  • CustomerRepository is autowired for interacting with the database
Customer.java:
package maxjava.model; import lombok.Data; @Data public class Customer { private String name; private String email; }
Some notes about Customer.java:
  • This is the object used in the request or response body on the Controller APIs
  • Use Lombok @Data for get and set
CustomerRepository.java:
package maxjava.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CustomerRepository extends JpaRepository<CustomerEntity, String> { }
Some notes about CustomerRepository.java:
  • Extends JpaRepository by providing the Entity type (Customer) and Primary Key type (String)
  • Mark this with @Repository as a bean
CustomerEntity.java:
package maxjava.repository; import jakarta.persistence.*; import lombok.Data; import java.util.Date; @Data @Entity @Table(name="Customer") public class CustomerEntity { @Id @Column(name="Name", length=50, nullable=false) private String name; @Basic @Column(name="Email") private String email; @Temporal(TemporalType.TIMESTAMP) @Column(name="CreatedDate") private Date createdDate; }
Some notes about CustomerEntity.java:
  • Use Lombok @Data for get and set
  • This is the mapped class for the table "Customer" with following chema:
    CREATE TABLE Customer ( Name VARCHAR(50) NOT NULL, Email VARCHAR(50) NULL DEFAULT NULL, CreatedDate TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (Name) )
Sample requests and responses:
  • Add a new Customer record:
    curl --request POST '<CONTEXT_PATH>/myapp/customer' --header 'Content-Type: application/json' --data-raw ' { "name": "Ethan", "email": "ethan@maxjava.net" }'
  • Retrieve the Customer record by name
    curl --request GET '<CONTEXT_PATH>/myapp/customer?name=Ethan'
    Response:
    { "name": "Ethan", "email": "ethan@maxjava.net" }
  • Updating the Customer record by name
    curl --request PUT '<CONTEXT_PATH>/myapp/customer' --header 'Content-Type: application/json' --data-raw ' { "name": "Ethan", "email": "ethan.new@maxjava.net" }'
  • Retrieve the record again by same name, the data is changed
    curl --request GET '<CONTEXT_PATH>myapp/customer?name=Ethan'
    Response:
    { "name": "Ethan", "email": "ethan.new@maxjava.net" }
  • deleting the Customer record by name
    curl --request DELETE '<CONTEXT_PATH>/myapp/customer?name=Ethan'