Saturday, September 28, 2024

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


// src/predominant/java/com/instance/iwreactspring/service/TodoService.java 
package deal 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 unit.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
  personal 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 deliver the TodoRepository class in. This will probably 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 want a strategy to get all of the to-dos within the database, and getTodos() does that for us. The Repository class makes it very simple, 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