Dozer中的地图集合大小

时间:2009-12-18 23:14:26

标签: java dozer

有没有办法在推土机中映射集合大小?

class Source {
    Collection<String> images;
}

class Destination {
  int numOfImages;
}

2 个答案:

答案 0 :(得分:3)

编辑我已经更新了我的答案,在现场级而不是在班级使用自定义转换器。

可能还有其他解决方案,但有一种方法可以使用Custom Converter。我已经为你的类添加了getter和setter,并编写了以下转换器:

package com.mycompany.samples.dozer;

import java.util.Collection;

import org.dozer.DozerConverter;

public class TestCustomFieldConverter extends 
        DozerConverter<Collection, Integer> {

    public TestCustomFieldConverter() {
        super(Collection.class, Integer.class);
    }

    @Override
    public Integer convertTo(Collection source, Integer destination) {
        if (source != null) {
            return source.size();
        } else {
            return 0;
        }
    }

    @Override
    public Collection convertFrom(Integer source, Collection destination) {
        throw new IllegalStateException("Unknown value!");
    }
}

然后,在custom XML mapping file

中声明它
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://dozer.sourceforge.net
          http://dozer.sourceforge.net/schema/beanmapping.xsd">
  <mapping>
    <class-a>com.mycompany.samples.dozer.Source</class-a>
    <class-b>com.mycompany.samples.dozer.Destination</class-b>
    <field custom-converter="com.mycompany.samples.dozer.TestCustomFieldConverter">
      <a>images</a>
      <b>numOfImages</b>
    </field>
  </mapping>        
</mappings>

通过此设置,以下测试成功通过:

@Test
public void testCollectionToIntMapping() {
    List<String> mappingFiles = new ArrayList<String>();
    mappingFiles.add("com/mycompany/samples/dozer/somedozermapping.xml");
    Mapper mapper = new DozerBeanMapper(mappingFiles);

    Source sourceObject = new Source();
    sourceObject.setImages(Arrays.asList( "a", "b", "C" ));

    Destination destObject = mapper.map(sourceObject, Destination.class);

    assertEquals(3, destObject.getNumOfImages());
}

答案 1 :(得分:0)

以下是使用ModelMapper解决此问题的方法:

ModelMapper modelMapper = new ModelMapper();
modelMapper.createTypeMap(Source.class, Destination.class).setConverter(
    new AbstractConverter<Source, Destination>() {
      protected Destination convert(Source source) {
        Destination dest = new Destination();
        dest.numOfImages = source.images.size();
        return dest;
      }
    });

此示例使用Converter作为Source和Destination类。

可以在http://modelmapper.org

找到更多示例和文档