title: Spring - How to apply a projection on a single resource?
body: <p>I am trying to apply a projection on an entity class called <code>Institute</code>.</p>
  
  <p>I have the following projection class defined.</p>
  
  <pre><code>@Projection(name = "instituteProjection", types = { Institute.class })
  public interface InstituteProjection {
  
      String getOrganizationName();
  
      Contact getContact();
  
      Address getRegisteredAddress();
  
      Address getMailingAddress();
  
  }
  </code></pre>
  
  <p>I followed an answer by Oliver Gierke <a href="https://stackoverflow.com/questions/29376090/how-to-apply-spring-data-projections-in-a-spring-mvc-controllers">link</a> and was able to return a collection resource with the projections when <code>http://localhost:8080/institutes</code> is called. I did this by implementing the following method in the service layer and then calling it using a REST controller.</p>
  
  <pre><code>@Autowired
  private ProjectionFactory projectionFactory;
  
  @Autowired
  InstituteTypeRepository instituteTypeRepo;
  
  @Override
  public PagedResources&lt;Institute&gt; getAllInstitutes(Pageable page) {
      Page&lt;?&gt; instituteList = instituteRepo.findAll(page).
              map(institute -&gt; projectionFactory.createProjection(InstituteListProjection.class, institute));
      PagedResources&lt;Institute&gt; instituteListPaged = pagedResourcesAssembler.toResource(instituteList);
      return instituteListPaged;
  
  }
  </code></pre>
  
  <p>Now how do I apply the same projection to an item resource when <code>http://localhost:8080/institutes/1</code> is called?</p>
  
  <p><strong>UPDATE 1:</strong></p>
  
  <p>Controller method to get a single resource</p>
  
  <pre><code>@RequestMapping(value = "institutes/{instituteId}", method = RequestMethod.GET,
          produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity&lt;?&gt; getInstitute(@PathVariable Long instituteId) {
      Institute institute = service.getInstitute(instituteId);
      return new ResponseEntity&lt;&gt;(institute, HttpStatus.OK);
  }
  </code></pre>
  
  <p><strong>UPDATE 2:</strong></p>
  
  <p>Service layer method to get the single resource from the repository</p>
  
  <pre><code>@Override
  public Institute getInstitute(Long instituteId) {
      Institute institute = instituteRepo.findOne(instituteId);
      return institute;
  }
  </code></pre>