Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic DTO converter Pattern

Tags:

java

dto

I have many DTO objects. Every dto class have the methods

  • convertDTO(Entity entity)
  • convertDTOList(List<Entity> entity)

I want to use a desing pattern for my dto object converter. Which desing pattern I can use and how?

Dozer framework is good. But I want to write a generic pattern.

like image 869
janatar Avatar asked Jul 01 '13 21:07

janatar


2 Answers

If you use Java8, I'd suggest to use DTO to domain converter pattern as suggested here

Below an implementation example:

GenericConverter

public interface GenericConverter<I, O> extends Function<I, O> {

    default O convert(final I input) {
        O output = null;
        if (input != null) {
            output = this.apply(input);
        }
        return output;
    }

    default List<O> convert(final List<I> input) {
        List<O> output = new ArrayList<O>();
        if (input != null) {
            output = input.stream().map(this::apply).collect(toList());
        }
        return output;
    }
}

ConverterDTO

public class AccountCreateRequestConverter implements GenericConverter<AccountCreateRequest, AccountOutput> {

    @Override
    public AccountOutput apply(AccountCreateRequest input) {
        AccountOutput output = new AccountOutput();

        output.setEmail(input.getEmail());
        output.setName(input.getName());
        output.setLastName(input.getLastName());        
        output.setPassword(input.getPassword());                                

        return output;
    }

}

Consumer

The consumer class:

class Consumer {

    @Inject
    AccountCreateRequestConverter accountCreateInputConverter;

    void doSomething() {

        service.registerAccount(accountCreateInputConverter.apply(input));

    }

}

The strength of this pattern come from the easiness to use, because you could pass either a single or a list of entities, in which there can be other nested DTO to convert using their dedicated converters inside the converter parent class. Something like this:

nested collection DTO converter example

class ParentDTOConverter {

    @Inject
    ChildDTOConverter childDTOConverter;

    void doSomething() {

        @Override
        public ParentDTOOutput apply(ParentDTOInput input) {
            ParentDTOOutput output = new ParentDTOOutput();
            output.setChildList(childDTOConverter.convert(input.getChildList()));
        }

    }

}
like image 88
Fabrizio Stellato Avatar answered Sep 22 '22 18:09

Fabrizio Stellato


There are many different solutions. You can find a discussion about it here Object Conversion Pattern

like image 31
Luis Rivera Avatar answered Sep 24 '22 18:09

Luis Rivera