0

Is it ok to use an Interace for converting between DTO and Entity?

public interface UserDto {
    public long getId();
    public String getName();
    public String getEmail();
    public String getPassword();
}

public interface UserEntity extends UserDto {
    public long getUuId();
}

2 Answers2

1

For most cases, I would say no because the properties are different between them and should be independent of each other hence a custom implementation with an interface is not the ultimate solution.

I'd recommend using mapstruct library instead, which also works with interfaces under the hood. You define the interface, and it will generate the boilerplate code for you, resulting in much more maintainable code:

@Mapper 
public interface UserMapper{
    @Mappings(
             @Mapping(target = "id", source = "id"),
             @Mapping(target = "name", source = "name"),
             @Mapping(target = "email", source = "email"),
             @Mapping(target = "password", source = "password")
            })

    UserEntity mapDtoToEntity(UserDto usertDto);
}

If your mappings are simple enough, go with ModelMapper or Spring's BeanUtils.copyProperties. If you really want to map them yourself, I'd suggest avoiding mixing them up with an interface and keeping them independent from each other.

gkatiforis
  • 1,588
  • 9
  • 19
1

Use de convert interface

ModelMapper is deprecated already, the interface converter is the best way.

import org.springframework.core.convert.converter.Converter;

public class UserEntityToUserDTO implements Converter<UserEntity, UserDTo>
    {
    
        @Override
        public UserDTo convert(UserEntity source) 
        {
            //map the fields to dto object
        }
        
    }