DTO pattern: Best way to copy properties between two objects

后端 未结 6 1305
死守一世寂寞
死守一世寂寞 2020-12-12 12:33

In my application\'s architecture I usually send the object or list of objects from the data access layer to the web layer via the service layer, in which these objects get

6条回答
  •  再見小時候
    2020-12-12 13:19

    I had an application that I needed to convert from a JPA entity to DTO, and I thought about it and finally came up using org.springframework.beans.BeanUtils.copyProperties for copying simple properties and also extending and using org.springframework.binding.convert.service.DefaultConversionService for converting complex properties.

    In detail my service was something like this:

    @Service("seedingConverterService")
    public class SeedingConverterService extends DefaultConversionService implements ISeedingConverterService  {
        @PostConstruct
        public void init(){
            Converter featureConverter = new Converter() {
    
                @Override
                public FeatureDTO convert(Feature f) {
                    FeatureDTO dto = new FeatureDTO();
                    //BeanUtils.copyProperties(f, dto,"configurationModel");
                    BeanUtils.copyProperties(f, dto);
                    dto.setConfigurationModelId(f.getConfigurationModel()==null?null:f.getConfigurationModel().getId());
                    return dto;
                }
            };
    
            Converter configurationModelConverter = new Converter() {
                @Override
                public ConfigurationModelDTO convert(ConfigurationModel c) {
                    ConfigurationModelDTO dto = new ConfigurationModelDTO();
                    //BeanUtils.copyProperties(c, dto, "features");
                    BeanUtils.copyProperties(c, dto);
                    dto.setAlgorithmId(c.getAlgorithm()==null?null:c.getAlgorithm().getId());
                    List l = c.getFeatures().stream().map(f->featureConverter.convert(f)).collect(Collectors.toList());
                    dto.setFeatures(l);
                    return dto;
                }
            };
            addConverter(featureConverter);
            addConverter(configurationModelConverter);
        }
    }
    

提交回复
热议问题