title: Map a dto to an entity retrieved from database if Dto has Id using MapStruct
body: <p>I'm using <strong>MapStruct</strong> to make <code>dto &lt;-&gt; entity</code> mapping. The same mappers are used to <em>create</em> <strong>and</strong> <em>update</em> entities from dtos. A verification of the dto's id is done to know whether a new entity must be created (id == null) or it should be retrieved from database (id != null) .</p>
  
  <p>I'm actually using <a href="http://mapstruct.org/documentation/stable/reference/html/#customizing-mappers-using-decorators" rel="noreferrer">MapperDecorator</a> as a workaround. Example : </p>
  
  <h2>Mapper</h2>
  
  <pre><code>@Mapper
  @DecoratedWith(UserAccountDecorator.class)
  public interface UserAccountMapper {
  
      UserAccountDto map(User user);
  
      User map(UserAccountDto dto);
  
      User map(UserAccountDto dto, @MappingTarget User user);
  }
  </code></pre>
  
  <h2>Decorator</h2>
  
  <pre><code>public abstract class UserAccountDecorator implements UserAccountMapper {
  
      @Autowired
      @Qualifier("delegate")
      private UserAccountMapper delegate;
  
      @Autowired
      private UserRepository userRepository;
  
      @Override
      public User map(UserAccountDto dto) {
          if (dto == null) {
              return null;
          }
  
          User user = new User();
          if (dto.getId() != null) {
              user = userRepository.findOne(dto.getId());
          }
  
          return delegate.map(dto, user);
      }
  
  }
  </code></pre>
  
  <p>But this solution becomes heavy due to the fact that a decorator must be created for each mapper. </p>
  
  <p>Is there any good solution to perform that ? </p>
  
  <hr>
  
  <p>I'm using : </p>
  
  <ol>
  <li>MapStruct : <strong>1.1.0</strong></li>
  </ol>