推土机 - 从列表到列表映射时,在列表中转换对象?

时间:2014-06-26 13:18:25

标签: java dozer

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

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

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

class AEntity {

 List<BEntity> bEntities;
}

class BEntity {
 Long produktId;
}

class ADto {
 List<BDto> bDtos;
}

class BDto {
 String produktId;
}

1 个答案:

答案 0 :(得分:2)

正如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;
    }
}