1. Overview

This article contains spring boot restful web services with JPA example. We have used MySQL as a database in this example. Spring boot is the first choice to develop Rest Service with JSON. Spring boot makes fast development using easy configuration with minimum requirements. Nowadays Rest API development is very popular because of microservice architecture application development. We have explained this example with different layers like Controller, Service, and Data Access Object layers which are best practice to write API or web application.

 2. Example

This example contains Rest Web service CRUD operation with JPA MySQL database. An example is a consist of Controllers which will handle all HTTP request, Service layer will help us to write business logic and DAO or Repository which will communicate with the database and persistence of data. In this example, we have used MySQL as a database.

 

Spring boot restful web services with JPA example

Spring boot restful web services with JPA example

 2.1 pom.xml

  • spring-boot-starter-data-jpa used for spring boot JPA support.
  • mysql-connector-java used for the MySQL connection, we may replace any other database connection drivers to change any other database like Postgres, Oracle or any other JPA supported database.
<?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>
    <groupId>spring-boot-example</groupId>
    <artifactId>spring-boot-hibernate-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <description>Spring boot restful web services with JPA example</description>
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <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>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>    
            <version>5.1.6</version>
        </dependency>
    </dependencies>
    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.2 application.properties

  • spring.datasource.* is data source related properties. spring.jpa.* is JPA related properties.
spring.datasource.url=jdbc:mysql://localhost/demo_database
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
# Naming strategy
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

2.3 SpringBootConfig

package com.javadeveloperzone;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
/**
 * Created by Java Developer Zone on 19-07-2017.
 */
@SpringBootApplication
@ComponentScan
// Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }
}

2.4 EmployeeController

  • @RestController will generate a response in JSON format. @RestController is a combination of @Controller + @ResponseBody.
  • @RequestMapping will handle the specific request,  value contains URL path, a method can be GET, POST, DELETE or any other method will is supported by HTTP.
  • While return List<Employee> or only Employee object then spring boot automatically convert to JSON Array and JSON respectively so we do not worry about to convert objects to JSON which will be managed by spring boot.
package com.javadeveloperzone.controller;
import com.javadeveloperzone.model.Employee;
import com.javadeveloperzone.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@RestController     // for rest response
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    // to add new employee
    @RequestMapping(value = "save",method = RequestMethod.POST)     // or user @PostMapping
    public Employee save(Employee employee){
        return employeeService.save(employee);
    }
    // list of all employee
    @RequestMapping(value = "listEmployee",method = RequestMethod.GET)   // or use @GetMapping
    public java.util.List<Employee> listEmployee() {
        return employeeService.findAll();
    }
    // delete specific employee using employee id
    @RequestMapping(value = "delete", method = RequestMethod.DELETE)        // or use @DeleteMapping
    public void delete(@RequestParam("id")long id){
         employeeService.delete(id);
    }
    // search employee start with name
    @RequestMapping(value = "startWithName/{name}")
    public java.util.List<Employee> findByName(@PathVariable("name")String name){
        return employeeService.findEmployeeByEmployeeNameStartingWith(name);
    }
    // search employee by role
    @RequestMapping(value = "findByRole/{role}")
    public java.util.List<Employee> findByRole(@PathVariable("role")String role){
        return employeeService.findEmployeeByEmployeeRole(role);
    }
}

2.5 EmployeeService

Here is the only signature of EmployeService so at time of Autowire spring boot will create Reference to Interface and Object of it’s implementation.

package com.javadeveloperzone.service;
import com.javadeveloperzone.model.Employee;
import java.util.List;
/**
 * Created by Lenovo on 04-04-2018.
 */
public interface EmployeeService {
    List<Employee> findEmployeeByEmployeeNameStartingWith(String name); // fetch list of Employee which start with
    List<Employee> findEmployeeByEmployeeRole(String role);         // fetch Employee by role
    List<Employee> findAll();
    Employee save(Employee employee);
    void delete(long employeeId);
}

2.6 EmployeeServiceImpl

Here is actually an implementation of EmployeeService interface, We are just performing CRUD operation so we do not have too much logic for business but we need to write actually business logic over here.

package com.javadeveloperzone.service;
import com.javadeveloperzone.dao.EmployeeDAO;
import com.javadeveloperzone.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * Created by Lenovo on 04-04-2018.
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeDAO employeeDAO;
    @Override
    public List<Employee> findAll() {
        return employeeDAO.findAll();
    }
    @Override
    public List<Employee> findEmployeeByEmployeeNameStartingWith(String name) {
        return employeeDAO.findEmployeeByEmployeeNameStartingWith(name);
    }
    @Override
    public List<Employee> findEmployeeByEmployeeRole(String role) {
        return employeeDAO.findEmployeeByEmployeeRole(role);
    }
    @Override
    public void delete(long employeeId) {
        Employee employee = employeeDAO.findOne(employeeId);
        employeeDAO.delete(employee);
    }
    @Override
    public Employee save(Employee employee) {
        return employeeDAO.save(employee);
    }
}

2.7 EmployeeDAO

Here is Data Access Object, It will communicate with database and convert SQL query result to POJO Class or Model Class. Please note that EmployeDAO is an interface, Then we should have one question how a query will be generated:

  • Spring boot automatically generate a query from method name here is
    • findAll query will be “SELECT * FROM EMPLOYEE
    • findEmployeeByEmployeeRole query will be “SELECT * FROM EMPLOYEE WHERE EMPLOYEE_ROLE =: ROLE
  • So spring JPA will generate a query based on the method name but spring boot JPA provides some standard for the method name. We can also write the custom query to fetch data. Here is more details explanation about spring boot JPA custom query
package com.javadeveloperzone.dao;
import com.javadeveloperzone.model.Employee;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
 * Created by Java Developer Zone on 03-08-2017.
 */
@Repository
@Transactional
public interface EmployeeDAO extends CrudRepository<Employee,Long> {
    List<Employee> findEmployeeByEmployeeNameStartingWith(String name); // fetch list of Employee which start with
    List<Employee> findEmployeeByEmployeeRole(String role);         // fetch Employee by role
    List<Employee> findAll();                           // fetch all Employee
}

2.8 Employee

package com.javadeveloperzone.model;
import javax.persistence.*;
/**
 * Created by Java Developer Zone on 03-08-2017.
 */
@Entity
@Table(name = "employee")
public class Employee {
    @Id                                                     // primary key
    @GeneratedValue(strategy = GenerationType.IDENTITY)     // auto increment
    @Column(name = "employeeId")
    private long employeeId;
    @Column(name = "employeeName")
    private String employeeName;
    @Column(name = "employeeRole")
    private String employeeRole;
    public long getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(long employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeeRole() {
        return employeeRole;
    }
    public void setEmployeeRole(String employeeRole) {
        this.employeeRole = employeeRole;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
}

2.9 Build Application

mvn spring-boot:run

Console log

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)
2018-04-04 23:49:05.541  INFO 44300 --- [           main] com.javadeveloperzone.SpringBootConfig   : Starting
2018-04-04 23:49:17.174  INFO 44300 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-04-04 23:49:17.336  INFO 44300 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-04-04 23:49:17.367  INFO 44300 --- [           main] com.javadeveloperzone.SpringBootConfig   : Started SpringBootConfig in 12.552 seconds (JVM running for 25.492)

2.10 Output

1. Add or Save Employee localhost:8080/save with FORM data.

Spring boot Restful web services with JPA example - add employee

Spring boot Restful web services with JPA example – add employee

2. list or fetch all Employee. localhost:8080/listEmployee

Spring boot Restful web services with JPA example - Fetch All Employee

Spring boot Restful web services with JPA example – Fetch All Employee

3. Delete Employee using localhost:8080/delete?id=18

Spring boot Restful web services with JPA example - Delete Employee

Spring boot Restful web services with JPA example – Delete Employee

3. Conclusion

In this article, We have learned that spring boot makes our ways easy to build Rest JSON or XML based web services. We have used postman tool to call JSON services. The code has been written in multiple layers so we can reuse of code and easy to understand for other developers also. We can also secure our web services, here is an example of how to secure web services

4. References

5. Source Code

spring boot JPA MySQL rest example.zip (52 KB)

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *