title: DTO conveter pattern in Spring Boot
body: <p>The main question is how to convert <strong>DTOs to entities</strong> and <strong>entities to Dtos</strong> without breaking <a href="https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)" rel="noreferrer">SOLID</a> principles. <br>
  For example we have such json:</p>
  
  <pre><code>{ id: 1,
    name: "user", 
    role: "manager" 
  } 
  </code></pre>
  
  <p>DTO is:</p>
  
  <pre><code>public class UserDto {
   private Long id;
   private String name;
   private String roleName;
  }
  </code></pre>
  
  <p>And entities are: <br></p>
  
  <pre><code>public class UserEntity {
    private Long id;
    private String name;
    private Role role
  } 
  public class RoleEntity {
    private Long id;
    private String roleName;
  }
  </code></pre>
  
  <p>And there is usefull <a href="https://bulldogjob.com/articles/287-converter-pattern-in-java-8" rel="noreferrer">Java 8 DTO conveter pattern</a>.</p>
  
  <p>But in their example there is no OneToMany relations. In order to create UserEntity I need get Role by roleName using dao layer (service layer). Can I inject UserRepository (or UserService) into conveter. Because it seems that converter component will break <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle" rel="noreferrer">SRP</a>, it must convert only, must not know about services or repositories.</p>
  
  <p>Converter example:</p>
  
  <pre><code>@Component
  public class UserConverter implements Converter&lt;UserEntity, UserDto&gt; {
     @Autowired
     private RoleRepository roleRepository;    
  
     @Override
     public UserEntity createFrom(final UserDto dto) {
         UserEntity userEntity = new UserEntity();
         Role role = roleRepository.findByRoleName(dto.getRoleName());
         userEntity.setName(dto.getName());
         userEntity.setRole(role);
         return userEntity;
     }
  
     ....
  </code></pre>
  
  <p>Is it good to use repository in the conveter class? Or should I create another service/component that will be responsible for creating entities from DTOs (like UserFactory)?</p>