Home > Net >  What is the best way to convert entity to dto? For Spring REST API Application
What is the best way to convert entity to dto? For Spring REST API Application

Time:09-29

I created an abstract class to generate the list of entities or dto using modelmapper in the inheriting class. Do you have any suggestions for a better way? For each class we need to create the toDTO and toEntity methods

public abstract class AbstractConverter<Entity,DTO> {

    @Autowired
    ModelMapper modelMapper;

    public List<Entity> toEntityList (Iterable<DTO> listDTO) {
        List<Entity> list = new ArrayList<Entity>();

        if(listDTO != null) {
            for (DTO dto:listDTO) {
                Entity entity = toEntity(dto);
                list.add(entity);
            }
        }
        return list;
    }
    
    public List<DTO> toDTOList (Iterable<Entity> listEntity) {
        List<DTO> list = new ArrayList<DTO>();

        if(listEntity != null) {
            for (Entity entity:listEntity) {
                DTO dto = toDTO(entity);
                list.add(dto);
            }
        }
        return list;
    }
}
@Component
public class UserConverter extends AbstractConverter<User,UserDTO> {

    public User toEntity(UserDTO userDTO) {
        if (userDTO != null) {
            return modelMapper.map(userDTO, User.class);
        }
        return null;
    }

    public UserDTO toDTO(User user) {
        if (user != null) {
            return modelMapper.map(user, UserDTO.class);        
        }
        return null;
    }
}

CodePudding user response:

I will suggest have a look at Spring's Beanutils.copyproperties() method.

CodePudding user response:

You should take a look at MapStruct which is a library focused on Java Beans mapping. For simple cases, it works great. If you have some more complex mapping it might get not that straightforward. Still, it is worth the try I would say. You can find some pretty good documentation about it:

I believe you can simplify your code with it instead of ModelMapper.

  • Related