'How to properly create non-persistant repositories in Spring Boot? [closed]

I want to store resources data in-memory (e.g. in a Map, non persistent) in a Spring Boot RESTful web service. I am new to Spring (Boot) and I am not sure what is the preferred approach to do this.

Is creating a Repository (@Repository) containing the resources the proper way to do this or is it preferred to create a Service, a Component or use another approach?

Let's say I want to have Todos with many-to-many relationships with Tags as below:

@RestController
@RequestMapping("/todos")
public class TodoController {
  @Autowired
  private TodoRepository todoRepository;
  @Autowired
  private TagRepository tagRepository;

  ...
}

Is it ok to reconstruct the relationships in the Controller class? Should this happen in an intermediate TodoService class?



Solution 1:[1]

Repositories are used with JDBC (or JPS, etc) to help you talk to a DB (persistent, like SQL, or in-memory, like H2). If you're not doing that, then you don't need a repository interface.

If you're storing info non-permanently and want to be able to inject that, I'd put that Map into a service class, as an instance variable. Then you can inject the service and access that Map wherever.

The pattern that I prefer is to inject the services into the controller, have very little in the controller other than the call to the service layer and the construction of the HTTPResponse, and put all of the logic into the service. (I would inject the repository/ies into the service to handle any DB interaction, but in your case, those service methods would interact with your map instance variable)/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1