title: Should I convert an entity to a DTO inside a Repository object and return it to the service layer?
body: <p>I am trying to get an answer to the two quite similar questions here:</p>
  
  <blockquote>
    <p>Should I convert an entity to a DTO inside a Repository object and return it to the Service Layer?</p>
  </blockquote>
  
  <p>or </p>
  
  <blockquote>
    <p>Is it okay to return DTO objects from the Repository Layer?</p>
  </blockquote>
  
  <p>Right now I am stuck in my Servlet (Servie Layer) that e.g. tries to retrieve all <code>Restaurant</code> objects from a <code>RestaurantOwnerRepository</code>:</p>
  
  <pre><code>// RestaurantOwnerService (Servlet)
  
  @Override
  @Transactional
  public List&lt;RestaurantDTO&gt; getAvailableRestaurants() {
  
      List&lt;Restaurant&gt; availableRestaurants = restaurantOwnerRepository.getRestaurants(getSessionId());
  
      return null;
  }
  </code></pre>
  
  <p>where <code>Restaurant</code> is a <code>@Entity</code> 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.</p>
  
  <p>That wouldn't be the case if I e.g. converted each <code>Restaurant</code> to a <code>RestaurantDTO</code> - but should I do that?</p>
  
  <p>Basically change:</p>
  
  <pre><code>// RestaurantOwnerRepository
  
  @Override
  public List&lt;Restaurant&gt; getRestaurants(String sessionId) {
  
      RestaurantOwner restaurantOwner = this.get(sessionId);
  
      // .. getting restaurants ..
  
      return availableRestaurants;
  }
  </code></pre>
  
  <p>to </p>
  
  <pre><code>// RestaurantOwnerRepository
  
  @Override
  public List&lt;Restaurant&gt; getRestaurants(String sessionId) {
  
      RestaurantOwner restaurantOwner = this.get(sessionId);
  
      // .. getting restaurants ..
  
      return ConvertEntity.convertRestaurants(availableRestaurants);
  }
  </code></pre>
  
  <p>and have a util <code>ConvertEntity</code> for <em>every</em> entity like this for example:</p>
  
  <pre><code>public class ConvertEntity {
  
      public static List&lt;RestaurantDTO&gt; convertRestaurants(List&lt;Restaurant&gt; restaurants) {
          // ...
      }
  
  }
  </code></pre>
  
  <p>but this just does not feel like the best solution to me.. what could I do here?</p>
  
  <hr>
  
  <p><strong>One important thing to mention</strong> would be that this comes form a GWT project. That means that I am using e.g. <code>RestaurantDTO</code> on the server and on the client side as it is contained inside a <em>shared</em> project. </p>