After reading this article, I change return value of service method entity into DTO.
But I'm little confused in this below situation.
Entity A
<- Repository A
<- Service A
Entity B
<- Repository B
<- Service B
Then , If Service B need to access entity A ,so call method in Service A. Since the result of that method is DTO ,not entity, I'm having a hard time dealing with DTO A in Service B.
Should I call repository A
in Service B
? or should I call Service A
in Service B
and use modelmapper to covert dto to entity in service B?
// Controller code
@RestController
public FooDTO getSomeFoo(){
return new FooDTO(service.getFoo())
}
// Service code
@Service
public Foo getFoo(){
return repository.find(~)
}
In my opinion, unless you really want to protect your entities to be changed elsewhere other than the corresponding Service, I would avoid DTOs in calls inside the service layer. This means that it is ok to return Entities in methods that you know that are called by other Services in your application, unless you really want to, most probably, over-engineer your application. Having said that you should return DTOs only in the methods that are called by your Controller layer so that they are used in your REST API (assuming you have one). Of course, this requires discipline and making sure you don't call methods on your Controller that are supposed to be called only by Services. There is an architecture that tries to tackle this (if you want to read more about it --> https://medium.com/@shivendraodean/software-architecture-the-onion-architecture-1b235bec1dec) and you can try to take advantage of package protected feature to guarantee this.
Should I call repository A in Service B?
Definitely not. You should never (never may be a strong word, but you should at least strive hard to avoid it) do this, otherwise your code will turn into a complete mess without any structure whatsoever.