mardi 19 décembre 2017

DTO conveter pattern in Spring Boot

The main question is how to convert DTOs to entities and entities to Dtos without breaking SOLID principles.
For example we have such json:

{ id: 1,
  name: "user", 
  role: "manager" 
} 

DTO is:

public class UserDto {
 private Long id;
 private String name;
 private String roleName;
}

And entities are:

public class UserEntity {
  private Long id;
  private String name;
  private Role role
} 
public class RoleEntity {
  private Long id;
  private String roleName;
}

And there is usefull Java 8 DTO conveter pattern.

But in their example there is no One To many relations. In order to create UserEntity I need get Role by roleName using dao layer (service layer). Can I inject UserRepository (UserService) to conveter. Because it seems that converter component will break SRP principle, it must convert only, do not know about services or repository.

Converter example:

@Component
public class UserConverterImpl implements UserConverter<UserEntity, UserDto> {
   @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 updateEntity(new Account(), dto);
   }

   ....

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)?

Aucun commentaire:

Enregistrer un commentaire