【问题标题】:Dozer - Having objects converted in a list while mapping from list to list?Dozer - 在从列表映射到列表时将对象转换为列表?
【发布时间】:2014-06-26 13:18:25
【问题描述】:

我们正在使用 Dozer 将实体映射到 dto 对象。

我们遇到以下问题:假设我们有一个 A 实体,它与 B 实体具有一对多的关系。映射时,我们希望将 B 实体中的字段 produktId(例如 1234)转换为 B Dto 中的修改值(例如 00001234)。

在从列表映射到列表时,是否可以在列表中转换对象?

class AEntity {

 List<BEntity> bEntities;
}

class BEntity {
 Long produktId;
}

class ADto {
 List<BDto> bDtos;
}

class BDto {
 String produktId;
}

【问题讨论】:

标签: java dozer


【解决方案1】:

正如 André 所建议的,自定义转换器在这里似乎很合适。对于API mapping,这样的东西应该适用于Dozer 5.5.1:

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import org.dozer.loader.api.BeanMappingBuilder;
import org.dozer.loader.api.FieldsMappingOptions;

public class MappingExample {

    private Mapper mapper;

    public ADto map(AEntity aEntity) {
        return getMapper().map(aEntity, ADto.class);
    }

    private Mapper getMapper() {
        if (mapper == null) {

            BeanMappingBuilder mappingBuilder = new BeanMappingBuilder() {
                @Override
                protected void configure() {
                    // Or just annotate getbEntities() in AEntity 
                    // with @Mapping("bDtos")
                    mapping(AEntity.class, ADto.class)
                            .fields("bEntities", "bDtos");

                    // Specify custom conversion for the Long field
                    mapping(BEntity.class, BDto.class)
                      .fields("produktId", "produktId",
                        FieldsMappingOptions.customConverter(
                                LongToStringConverter.class));
                }
            };

            // Pass the custom mappings to Dozer
            DozerBeanMapper beanMapper = new DozerBeanMapper();
            beanMapper.addMapping(mappingBuilder);
            mapper = beanMapper;
        }

        return mapper;
    }
}

转换器可能看起来像这样:

import org.dozer.CustomConverter;

public class LongToStringConverter implements CustomConverter {
    @Override
    public Object convert(Object existingDestFieldValue, Object srcFieldValue,
                          Class<?> destinationClass, Class<?> sourceClass) {
        if (srcFieldValue != null && srcFieldValue instanceof Long
                && String.class.equals(destinationClass)) {
            return String.format("%04d", (Long)srcFieldValue);
        }

        return null;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多