I am learning Java in 2020 – Beginner – Simple Spring REST Service Setup with In-memory DB

Operation System : Windows 10

IDE : IntelliJ

Requirements : Java 8 > , Postman ( Rest API Testing)

Book | Tutorial : youtube tutorial

Java version : 12

Git Project : Here

Starter Project: Here

Parts: Part 2

Goal

  • Learn how to setup a spring rest application
  • Learn how to add dependencies in the pom.xml file

Pseudo-code

  • Go to start.spring.io
  • Add dependencies ( Spring Web )
  • download spring project
  • Unzip
  • Open IntelliJ
  • File → open → pom.xml of unzipped file click → open as project
  • Model, Controllers, Service

What I learned

3-Tier application

This comprises three layers, namely, the presentation – , the application – and the data – layer. Furthermore it describes the main areas that make up a lot of softwares. For instance, the presentation layer handles what the end user sees and interacts with. While the application is the business logic, which is usually the routes, controllers, middlewares etc the server communicates with the data layer ( e.g. a MySQL databank) and the presentation layer .

RESTful web services

The REST stands for Representational State transfer. Most of the applications you navigate on the web make use of this Rest standard. It sets specific rules which define how a web application interacts with a resource using a protocol e.g. HTTP. By means of this standard, one can access a specific resource in a specific format or manipulate a resource or make the resource completely unavailable. Web services ( to my understanding, simply backends) that implement the REST architecture are called Restful web services.

Dependency Injection

When an object receives another object that it depends on without having to generate the object itself, it is called dependency injection. The object on the receiving end is called the client, while the object being given is termed the service. The middleman or the one that mediates the transfer is called the injector. This is the extent to how I understand this concept, so bear with me.

Spring framework

This framework provides templates for developers working with API such as JPA. It saves us the time and brain-itching when programming the foundations of backend architecture.

Spring Boot

Based on my 5 min blog research,it is mainly used to build REST APIs in Java.

Conception

Model

Todo

Completed

boolean , default false, valid

Title

string , not null, not empty, valid

Service ( Business Logic)

addTodo

Creates a new todo object

removeTodoById

Removes an existing todo by id

updateTodoById

Updates the content of a todo object

selectTodoById

Retrieves a todo

selectAllTodos

Fetches all todos and returns as a list

Controllers

POST, GET

/api/v1/todos/

PATCH, DELETE

/api/v1/todos/{id}

Note : No validation logic added

Solution

Models

Simply the  objects created and manipulated in the business logic. Here the only object we will be working with is a todo object, which has the following structure:

package com.example.demo.model;

import java.util.UUID;

public class Todo {
    private final UUID id;
    private final String title;
    private boolean isComplete = false;

    public Todo(UUID id, String  title,  boolean isComplete){
        this.title = title;
        this.isComplete  = isComplete;
        this.id = id;
    }

    public String getTitle() {
        return title;
    }
    public boolean getIsComplete(){
        return isComplete;
    }

    public UUID getId() {
        return id;
    }
}

Service

This service handles the main operations such as creating objects, updating database, manipulating objects, logging operations etc.

package com.example.demo.service;

import com.example.demo.dao.ITodoService;
import com.example.demo.model.Todo;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
@Service
public class TodoService implements ITodoService {
    private List<Todo> todos = new ArrayList<>();

    @Override
    public void addTodo(@JsonProperty("title") String title, @JsonProperty("isCompleted") boolean isCompleted) {
        Todo todo = new Todo(UUID.randomUUID(), title, isCompleted);
        todos.add(todo);
    }

    @Override
    public Todo patchTodo(UUID id, Todo patch) {
        Todo newtodo = new Todo(id, patch.getTitle(), patch.getIsComplete());
        List<Todo> newtodos = this.todos.stream().map(todo -> todo.getId().equals(id)? newtodo : todo).collect(Collectors.toList());
        this.todos = newtodos;
        return newtodo;
    }

    @Override
    public int deleteTodo(UUID id) {
        List<Todo> newtodos = this.todos.stream().filter(todo -> !todo.getId().equals(id)).collect(Collectors.toList());
        this.todos = newtodos;
        return 0;
    }

    @Override
    public List<Todo> getTodos() {
        return this.todos;
    }

    @Override
    public Todo selectTodo(UUID id) {
       Todo match =  todos.stream().filter(todo -> todo.getId().equals(id)).findFirst().orElse(null);
       return match;
    }
}

Controller

This is usually where all the REST request are placed.

package com.example.demo.controller;

import com.example.demo.model.Todo;
import com.example.demo.service.TodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/todos")
public class TodoController {
    @Autowired
    private TodoService todoService;

    @GetMapping("/")
    public List<Todo> selectAllTodos(){
        return this.todoService.getTodos();
    }

    @PostMapping("/")
    public void addTodo(@RequestBody  Todo todo){
        this.todoService.addTodo(todo.getTitle(), todo.getIsComplete());
    }
    @PatchMapping("/{id}")
    public Todo patchTodo(@PathVariable("id") UUID id, @RequestBody  Todo patch){
        return this.todoService.patchTodo(id, patch);
    }
    @DeleteMapping("/{id}")
    public void deleteTodo(@PathVariable("id") UUID id){
        this.todoService.deleteTodo(id);
    }


}

Author Notes

This is most likely not the cleanest implementation, just a heads up.

Links

  1. 3-tier application architecture
  2. RESTful Web Services
  3. Dependency injection
  4. Spring Framework Annotations
  5. Java 8 Stream Tutorial
  6. Java 8 stream: replace single item in streamed collection