문제
도저에서 수집 크기를 매핑하는 방법이 있습니까?
class Source {
Collection<String> images;
}
class Destination {
int numOfImages;
}
해결책
편집하다: 클래스 수준이 아닌 필드 레벨에서 사용자 정의 변환기를 사용하도록 답변을 업데이트했습니다.
다른 해결책이있을 수 있지만이를 수행하는 한 가지 방법은 사용자 정의 변환기. 수업에 게스터와 세터를 추가하고 다음 컨버터를 썼습니다.
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!");
}
}
그런 다음 a 사용자 정의 XML 매핑 파일:
<?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());
}
다른 팁
다음은 이것을 해결하기위한 접근법입니다 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;
}
});
이 예제는 소스 및 대상 클래스에 변환기를 사용합니다.
더 많은 예와 문서를 찾을 수 있습니다 http://modelmapper.org
제휴하지 않습니다 StackOverflow