Spring Boot RESTful Web Service with JPA and MySQL

In this article, you will learn how to build a RESful webs service in Spring Boot using JPA repository and MySQL database. Here we will create a RESTful web service that retrieves the data from the database based on the query and response in JSON format. Spring Boot uses the spring-boot-starter-data-jpa to create the database connection using Hibernate. You can define your database credentials in the application.yml or application.properties.

Here we can only fetch the records from the database. If you want to fetch particular employee records, your end-point URL will be:


you will get the response as given below…

    "empNo": 7698,
    "name": "BLAKE",
    "job": "MANAGER"

And to fetch all employee records, your end-point URL will be:


Technologies Used

Find the list of all technologies used in this application.

  • Spring Tool Suite 4
  • JDK 8
  • Maven 3
  • Spring-boot 2.0.5.RELEASE
  • MySQL Database

Database Schema

Find the table structure and insert statement of MySQL database used in this example.

/*`emp` table structure */
  `empno` decimal(4,0) NOT NULL,
  `ename` varchar(10) DEFAULT NULL,
  `job` varchar(9) DEFAULT NULL,
  `mgr` decimal(4,0) DEFAULT NULL,
  `hiredate` date DEFAULT NULL,
  `sal` decimal(7,2) DEFAULT NULL,
  `comm` decimal(7,2) DEFAULT NULL,
  `deptno` decimal(2,0) DEFAULT NULL

/*Data for the table `emp` */

insert  into `emp`(`empno`,`ename`,`job`,`mgr`,`hiredate`,`sal`,`comm`,`deptno`) values ('7369','SMITH','CLERK','7902','1980-12-17','800.00',NULL,'20'),('7499','ALLEN','SALESMAN','7698','1981-02-20','1600.00','300.00','30'),('7521','WARD','SALESMAN','7698','1981-02-22','1250.00','500.00','30'),('7566','JONES','MANAGER','7839','1981-04-02','2975.00',NULL,'20'),('7654','MARTIN','SALESMAN','7698','1981-09-28','1250.00','1400.00','30');

Dependencies Required

Building a RESTful web service in Spring Boot, you need the following dependencies. Add the following code in your pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

		<relativePath /> <!-- lookup parent from repository -->






Project Structure

Final project structure of our application in STS ide will look like as follows.

Spring Boot RESTful Web Services with JPA and MySQL

Application Configuration

Configure the database credentials like database name, username, password, and Tomcat server port, etc in the application.yml file.

  port: 8888

    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/websparrow
    username: root
    hibernate.ddl-auto: update
    generate-ddl: true
    show-sql: true

Model Class

Create a model class for the Emp table. This class contains the table name and it columns name that you want to fetch from the database.

package org.websparrow.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "emp")
public class Employee {

	// TODO- Generate Getters and Setter of all the fields

	@Column(name = "empno")
	private Integer empNo;
	@Column(name = "ename")
	private String name;
	@Column(name = "job")
	private String job;


EmployeeRepository interface extends the JpaRepository. JPA is the standard way of persisting Java objects into relational databases. By extending the JpaRepository interface, our EmployeeRepository has the capabilities to query with the database like listing the all the employees, find the employee by id, etc.

package org.websparrow.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.websparrow.model.Employee;

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {


Controller Class

In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the @RestController annotation, and the EmployeeController handles GET requests.

package org.websparrow.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.websparrow.model.Employee;
import org.websparrow.repository.EmployeeRepository;

public class EmployeeController {

	EmployeeRepository empRepo;

	@GetMapping(value = "/all")
	public List<Employee> getAll() {
		return empRepo.findAll();

	@GetMapping(value = "/{id}")
	public Optional<Employee> getOne(@PathVariable("id") Integer id) {
		return empRepo.findById(id);


Execute It

Create an App class and run it.

package org.websparrow;

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

public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);

Test the Service

To fetch the specific employee records, visit http://localhost:8888/employee/7839, where 7839 is employee id and you will get:

    "empNo": 7839,
    "name": "KING",
    "job": "PRESIDENT"

As Spring uses the Hibernate to query from the database, you can see the HQL in your console log.

Hibernate: select employee0_.empno as empno1_0_0_, employee0_.job as job2_0_0_, employee0_.ename as ename3_0_0_ from emp employee0_ where employee0_.empno=?

And to fetch all employee records, visit http://localhost:8888/employee/all

        "empNo": 7369,
        "name": "SMITH",
        "job": "CLERK"
        "empNo": 7499,
        "name": "ALLEN",
        "job": "SALESMAN"
        "empNo": 7521,
        "name": "WARD",
        "job": "SALESMAN"


  1. Spring Boot RESTful Web Service Example
  2. JPA Repositories
  3. Interface JpaRepository<T,ID>

Similar Posts

About the Author

Atul Rai
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.