Reputation: 1168
I am working on a standard Spring Boot (with Spring Web and Spring Data) Rest Web service and got into this situation.
If for example I have two entities:
And they have a Many-to-many releationship. How would their services look?
Option 1:
Option 2:
I was thinking Option 2 because every repository is interfaced through its respective service, but the following problem comes from that:
If I want the services to only expose DTOs and need an entity of User inside my TeamService for Many-to-many to work using Hibernate(I need a reference not only id). I have to either do workarounds or expose an entity from the UserService.
What would be the more clear solution or am I getting something mixed up in my logic?
Edit:
Some context:
If i need a method like addUserToTeam(Integer userId, Integer teamId) inside TeamService I would need to get the user entity by id in order to add it to the team list of users.
Upvotes: 2
Views: 577
Reputation: 3324
It depends
. Depends on your business use-cases .. rules...
Between Team
and User
is there some kind of owner ?
Is your business required to create a team before push users inside ? or let users been created in an independant way ?
Maybe when you have to create a user you have to assign him a team .. maybe not..
Imagine you have to create a Team
before add Users
into you can now considered Team
as an aggregate concept (look at Domain driven design aggregate).
A DDD aggregate is a cluster of domain objects that can be treated as a single unit.
And so going with these objects :
So "in this case" no need for USerService or UserRepo
. Each time you want to add/delete/update a user you will do through the Team
object/aggregate. And so registration of a new User
will be done through
team.addUser(user);
teamRepository.update(team team)
If now both concepts are totally independent you could see them as 2 separate aggregates and both will have their own repository.
Concerning the service as team and users are related concepts having 2 services could be overkill.
A single service to maintain lifecyle and consistency between Team
and Users
sounds more suitable.
So :
I just say that one service = one aggregate
is not a rule... Services are facade and facade can wrap a domain model composed of multiple aggregates.Keep cohesion high
is the rule.
Upvotes: 2
Reputation: 339
The repositories are bound to the database structures.
The services are related to the business logic that you need.
For example a UserService could include methods to get Teams or Users if you thing that belongs to the same business logic.
Upvotes: 1