title: Spring REST Hibernate Application Design
body: <p><strong>Environment :</strong> </p>
  
  <p>Spring 4 REST </p>
  
  <p>Spring MVC </p>
  
  <p>Hibernate  </p>
  
  <p><strong>Issue :</strong> </p>
  
  <p>We are developing an application with below stack.</p>
  
  <p><a href="https://i.stack.imgur.com/RR8O9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RR8O9.png" alt="enter image description here"></a></p>
  
  <p>The Spring REST web service will expose APIs for client which will display it on UI (ASP .NET ) . The response is sent in JSON.</p>
  
  <p>Consider below scenario :</p>
  
  <p>Client calls REST api to get User with ID. The dao layer fetches User entity and will be delievred to client.</p>
  
  <p>And below issues/observations for above scenario : </p>
  
  <ol>
  <li><p>Since User can have another entities related with it throgh Hibernate mapping (like userRoles using oneToMany), these entities also need to be fetched, else LazyInitialization exception is thrown since UI tries to access these collections through User object.</p></li>
  <li><p>Not all properties in User object will be required in response (e.g: some requests won't need roles a user have). </p></li>
  </ol>
  
  <p>Considering above picture in mind , what is the best design approach to send User object (or response) to client through Spring REST?? </p>
  
  <ol>
  <li><p>Create an intermediate layer of objects (like DTOs) mimicking entity objects. Have this DTOs populated in Service layer as per requirement. Since service layer runs inside transaction issue number 1 will be resolved. But this requires extra copying between entity and DTOs</p></li>
  <li><p>Handle issue number 1/2 at Hibernate entity / query level (join fetch queries or revamping mapping) and exclude properties not required in response through annotations like: @JsonIgnore. But this approach is not flexible and requires very careful design of entity classes</p></li>
  </ol>
  
  <p>Can anybody please comment on this? 
  Is there any better alternative available?</p>