Big Data

Full-stack development with Java, React, and Spring Boot, Part 2




// src/main/java/com/example/iwreactspring/service/TodoService.java 
package com.example.iwreactspring.service;

import java.util.List;
import java.util.ArrayList;
import com.example.iwreactspring.model.TodoItem;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.Document;

import com.example.iwreactspring.repository.TodoRepository;

@Service
public class TodoService {

  @Autowired
  private TodoRepository todoRepository;

  public List getTodos() {
    return todoRepository.findAll();
  }

  public TodoItem createTodo(TodoItem newTodo) {
    TodoItem savedTodo = todoRepository.save(newTodo);
    return savedTodo;
  }
  public TodoItem getTodo(String id) {
    return todoRepository.findById(id).orElse(null);
  }

  public boolean deleteTodo(String id) {
    TodoItem todoToDelete = getTodo(id);
    if (todoToDelete != null) {
      todoRepository.deleteById(id);
      return true;
    } else {
      return false;
    }
  }
  public TodoItem saveTodo(TodoItem todoItem) {
    TodoItem savedTodo = todoRepository.save(todoItem);
    return savedTodo;
  }
}

We annotate this class with @Service to denote it as a service class. Again, this is not strictly required, because Spring can use the class as an injected bean without the annotation, but annotating the class makes things more descriptive. Next, we use @AutoWired to bring the TodoRepository class in. This will be populated by Spring based on the class type, which is the com.example.iwreactspring.repository.TodoRepository we saw earlier.

By default, Spring uses singleton injection (one instance of the injected bean class), which works well for us.

CRUD operations on the service class

Each method on this class is dedicated to performing one CRUD operation using the repository. For example, we need a way to get all the to-dos in the database, and getTodos() does that for us. The Repository class makes it very easy, too: return todoRepository.findAll() returns all the records (aka documents) in the todo collection (aka, database).



READ SOURCE

This website uses cookies. By continuing to use this site, you accept our use of cookies.