-10.4 C
New York
Monday, December 23, 2024

Full-stack growth with Java, React, and Spring Boot, Half 2




// src/principal/java/com/instance/iwreactspring/service/TodoService.java 
bundle com.instance.iwreactspring.service;

import java.util.Record;
import java.util.ArrayList;
import com.instance.iwreactspring.mannequin.TodoItem;
import org.springframework.stereotype.Service;

import org.springframework.beans.manufacturing facility.annotation.Autowired;
import com.mongodb.consumer.MongoClient;
import com.mongodb.consumer.MongoClients;
import com.mongodb.consumer.MongoCollection;
import com.mongodb.consumer.MongoDatabase;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.Doc;

import com.instance.iwreactspring.repository.TodoRepository;

@Service
public class TodoService {

  @Autowired
  non-public TodoRepository todoRepository;

  public Record<TodoItem> 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 indicate it as a service class. Once more, this isn’t strictly required, as a result of Spring can use the category as an injected bean with out the annotation, however annotating the category makes issues extra descriptive. Subsequent, we use @AutoWired to convey the TodoRepository class in. This can be populated by Spring primarily based on the category sort, which is the com.instance.iwreactspring.repository.TodoRepository we noticed earlier.

By default, Spring makes use of singleton injection (one occasion of the injected bean class), which works effectively for us.

CRUD operations on the service class

Every technique on this class is devoted to performing one CRUD operation utilizing the repository. For instance, we’d like a technique to get all of the to-dos within the database, and getTodos() does that for us. The Repository class makes it very straightforward, too: return todoRepository.findAll() returns all of the data (aka paperwork) within the todo assortment (aka, database).

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles