Spring Boot allows us to quickly create Spring based projects with least configuration. It also allows us to work with databases, easily and efficiently without having to write SQL queries in code.

To know more about Spring Boot, please click here.

In this example, we will create a REST API using Spring Boot. We will be creating basic CRUD (Create, Read, Update, Delete) operations on User entity.

REST API URLs have following pattern:

Request Type URL Purpose
POST /user Create new user
PUT /user/1 Update user
GET /user Read all records
GET /user/1 Read single user
DELETE /user/1 Delete single user

First we need to setup following:

  1. A new Spring Boot project, you can follow the above provided link.
  2. MySQL to be installed on the system.
  3. Create a database named springboot in MySQL.
  4. Create a new user named spring with password boot which has permission to access the database.
    (You can use any database or user of your choice as well)

Here is our pom.xml file with all the necessary dependencies.

pom.xml

<?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>com.first</groupId>
  <artifactId>boot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>FirstSpringBoot</name>
  <description>Demo project for Spring Boot</description>

  <parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>1.4.2.RELEASE</version>
     <relativePath /> <!-- lookup parent from repository -->
  </parent>

  <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
     <java.version>1.8</java.version>
  </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-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!-- jackson for converting java objects to json -->  
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <!-- ************** database dependencies *********** -->
 
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
 
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
 
    <!-- ************** mysql and hibernate dependencies *********** -->
  </dependencies>

  <build>
    <plugins>
      <plugin>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
 </build>
</project>

Next we will specify our database settings in the application.properties file.

src/main/resources/application.properties

spring.datasource.url= jdbc:mysql://localhost:3306/springboot
spring.datasource.username=spring
spring.datasource.password=boot

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=create-drop

Next, we will create our User entity class that corresponds to users table in database.

Create a new package named: com.first.boot.entity

Create User.java in this package with following code:

User.java

package com.first.boot.entity;

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

@Entity
@Table(name="users")
public class User {
   @Id
   @GeneratedValue(strategy=GenerationType.IDENTITY)
   private Integer id;
 
   private String gender;
   private String name;
   private String email;

   public User(){
   }
   public User(String email, String name, String gender) {
     this.email = email;
     this.gender = gender;
     this.name = name; 
   }
 
   public Integer getId() {
     return id;
   }
   public void setId(Integer id) {
     this.id = id;
   }
 
   public String getGender() {
     return gender;
   }
   public void setGender(String gender) {
     this.gender = gender;
   }
 
   public String getName() {
     return name;
   }
   public void setName(String name) {
     this.name = name;
   }
 
   public String getEmail() {
     return email;
   }
   public void setEmail(String email) {
     this.email = email;
   }
}

One of the great features of Spring Data is to automatically create implementation of methods representing database operations. For example, if we want to search a single record by email, we just have to declare a method like this:

User findByEmail(String email);

Yes, we don’t have to write any further code and the functionality will be automatically available to our code. Isn’t it great!

Spring Boot uses Spring Data JPA (Java Persistence API) that allow us to handle database operations without creating DAO classes. For this, we need to define our repository interface that extends the CrudRepository interface.

To learn more about Spring data abstraction and repositories, follow this link:

http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

So, now we will create a repository class that provides all the default functionalities of an entity.

Create a new package named com.first.boot.repository.

Create a new file named UserRepository.java in the above package with following code:

UserRepository.java

package com.first.boot.respository;

import org.springframework.data.repository.CrudRepository;
import com.first.boot.entity.User;

public interface UserRepository extends CrudRepository<User, Integer>{
   User findByEmail(String email);
}

The last step is to create controller for our methods.

Create file UserController.java in com.first.boot.controller and add following code:

package com.first.boot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.first.boot.entity.User;
import com.first.boot.respository.UserRepository;
@RestController
@RequestMapping("/user")
public class UserController {
   @Autowired
   private UserRepository userRepo;
 
   @RequestMapping(method = RequestMethod.GET)
   public List<User> getAll() {
       return (List<User>) userRepo.findAll();
   }
   /**
    * POST /create --> Create a new user and save it in the database.
    */
   @RequestMapping(method = RequestMethod.POST)
   @ResponseBody
   public String create(@RequestBody User user) {
      userRepo.save(user);
      String userId = String.valueOf(user.getId());
      return userId;
   }

   /**
    * DELETE / --> Delete the user having the passed id.
    */
   @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
   @ResponseBody
   public String delete(@PathVariable Integer id) {
      userRepo.delete(id);
      return "deleted";
   }

   /**
    * GET /id --> Read the user with given id.
    */
   @RequestMapping(value = "/{id}", method = RequestMethod.GET)
   @ResponseBody
   public User getUser(@PathVariable Integer id) {
      User user = userRepo.findOne(id);
      if (user != null)
          return user;
      else
          return null;
   }
   /**
    * GET /get-by-email --> Return user by email
    */
   @RequestMapping("/get-by-email/{email}")
   @ResponseBody
   public User getByEmail(@PathVariable String email) {
      User user = userRepo.findByEmail(email);
      if (user != null)
         return user;
      else
         return null;
   }

   /**
    * PUT /{id} --> Update the email and the name for the user in the
    * database having the passed id.
    */
   @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
   @ResponseBody
   public String updateUser(@PathVariable Integer id, @RequestBody User userRequest) {
      User user = userRepo.findOne(id);
      if (user != null) {
         user.setEmail(userRequest.getEmail());
         user.setName(userRequest.getName());
         user.setGender(userRequest.getGender());

         userRepo.save(user);

         return "User succesfully updated!";
      } else
         return "User not found";
   }
}

Our code is ready at this moment. In STS, right click on your project, Run As => Spring Boot App. Using POSTMAN, we can test our API with following requests:

POST           http://localhost:8080/user/create       (Pass email, name, gender in Request Body)

GET             http://localhost:8080/user/2

GET             http://localhost:8080/user

GET             http://localhost:8080/user/get-by-email/a@b.com

DELETE      http://localhost:8080/user/1

PUT             http://localhost:8080/user/4      (Pass email, name, gender in Request Body)