I am trying to get an answer to the two quite similar questions here:
Should I convert an entity to a DTO inside a Repository object and return it to the Service Layer?
or
Is it okay to return DTO objects from the Repository Layer?
Right now I am stuck in my Servlet (Servie Layer) that e.g. tries to retrieve all Restaurant
objects from a RestaurantOwnerRepository
:
// RestaurantOwnerService (Servlet)
@Override
@Transactional
public List<RestaurantDTO> getAvailableRestaurants() {
List<Restaurant> availableRestaurants = restaurantOwnerRepository.getRestaurants(getSessionId());
return null;
}
where Restaurant
is a @Entity
annotated class - which appears to be the first thing I shouldn't do because the Service Layer does now know about a very low-level object which imho violates the attempt to abstract my data in each layer.
That wouldn't be the case if I e.g. converted each Restaurant
to a RestaurantDTO
- but should I do that?
Basically change:
// RestaurantOwnerRepository
@Override
public List<Restaurant> getRestaurants(String sessionId) {
RestaurantOwner restaurantOwner = this.get(sessionId);
// .. getting restaurants ..
return availableRestaurants;
}
to
// RestaurantOwnerRepository
@Override
public List<Restaurant> getRestaurants(String sessionId) {
RestaurantOwner restaurantOwner = this.get(sessionId);
// .. getting restaurants ..
return ConvertEntity.convertRestaurants(availableRestaurants);
}
and have a util ConvertEntity
for every entity like this for example:
public class ConvertEntity {
public static List<RestaurantDTO> convertRestaurants(List<Restaurant> restaurants) {
// ...
}
}
but this just does not feel like the best solution to me.. what could I do here?
One important thing to mention would be that this comes form a GWT project. That means that I am using e.g. RestaurantDTO
on the server and on the client side as it is contained inside a shared project.