V
V
Valeriy_Morozov2022-02-16 14:43:38
Java
Valeriy_Morozov, 2022-02-16 14:43:38

Can a Service have repositories of other classes?

Let's say I have Entity A and Entity B. Can I directly access the Entity A repository from Service B? Or should I do it like this Service B -> Service A -> Repository A?

The problem is that I have all DTO services, and Service B needs normal objects to work, what should I do in this case? Is it really possible to create separate exactly the same methods simply without an envelope in the DTO?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Orkhan, 2022-02-16
@Valeriy_Morozov

Can I directly access the Entity A repository from Service B?

Yes, you can. Another question is whether it's good.
Or should I do it like this Service B -> Service A -> Repository A?

I prefer this way.
The reason is as follows:
Here, imagine that at the service level you get Optional<T>from the repository and if the object is not found, then at the service level you throw an exception orElseThrow(). Well, then ExceptionHandler catches the exception and gives the appropriate error code and message to the front.
If you decide to go from service A to repository B, then in fact you need to get the object again and throw an exception if it is not found, and this is code duplication...
Pseudocode:
ServiceA {
@Autowired
RepoB repoB;
@Autowired
ServiceB serviceB;

// 1 вариант
List<Job> doSomeJob1(String email){
User user =  repoB.findUserByEmail(email).orElseThrow(UserNotFoundException::new);
return user.getJobs();
}

// 2 вариант
List<Job> doSomeJob2(String email) {
User user = serviceB.getUserByEmail(email);
return user.getJobs();
}

RepoB {
Optional<User> findUserByEmail(String email);
}

ServiceB {
@Autowired
RepoB repoB;

User getUserByEmail(String email){
return repoB.findUserByEmail(email).orElseThrow(UserNotFoundException::new);
}

}

In the second option, we did not have to write logic and throw an exception.
And so much depends on the project, how it is customary to work in a team, etc.
The problem is that I have all DTO services, and Service B needs normal objects to work, what should I do in this case? Is it really possible to create separate exactly the same methods simply without an envelope in the DTO?

I usually do it differently. I am returning objects from services. And if I need DTOs, then there is a separate MapperService service that accepts a generic and returns the corresponding DTOs.

M
Michael, 2022-02-16
@Akela_wolf

Technically, no one bothers you to do this.
Architecturally - you need to look at a specific project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question