Issue
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
My opinion on that is pretty straightforward.
If you are doing a basic CRUD application with not a lot of knowledge, but just a way to interact with a Database, then you don't really need to rely on a Service
, and then yes, having a dependency from your Controller
to your Repository
is good.
Let's take an example: When you add a new Todo to your DB, do you always create a new Tag ? If yes, then maybe those two Entities are linked together and should be adressed by a central way, a service. This way, you ensure the person creating Todo will also create the associated Tags. But if those 2 Entities have nothing in common, then keeping them separated works just fine.
About your other questions, the Repository
thing. You can easily code what you have in mind. In spring, if you look at the code of the annotation @Repository
, you will see that it is nothing more than a @Component
. The term Repository
is only here to help you and your team understanding your code base by easily identifying the role of each class. By definition, a Repository
is an access to your Domain object, in your case Todo
. No matter what is the persistance system behind that, this is just an access to your Domain Object.
Here is an example of you can do this.
public interface TodoRepository {
int save(Todo todo);
Todo findById(int totoId);
}
@Repository
public class InMemoryTodoRepository implements TodoRepository {
private Map<int, Todo> todos = new HashMap<>();
public Todo save(Todo todo) {
int newId = // generate new Id;
todos.put(newId, todo)
return newId;
}
public Todo findById(int totoId) {
return todos.get(todoId);
}
}
This way, when you will to change your InMemorySystem to a database of I don't know what, you will just have to make a new class implementing the interface, and you will be good to go, a.k.a Low coupling
Answered By - RUARO Thibault
Answer Checked By - Robin (JavaFixing Admin)