JAVA - 使用 ModelMapper 映射表达式,但不使用 setter

Fra*_*lik 1 java collections setter modelmapper

我正在使用 ModelMapper 将 JPA 实体映射到 DTO。我在实体上有集合 dto 是由 wsimport 从 wsdl 文件生成的,但集合的设置器不会生成

public class sampleEntity{
    private String name;
    private Collection<String> list;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }    

    public Collection<String> getList() {
        return list;
    }

    public void setList(Collection<String> list) {
        this.list = list;
    }
}

public class sampleDTO{
    private String name;
    private Collection<String> list;

    //getters & setters

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Collection<String> getList() {
        return list;
    }
//no collection setters with jaxb!!! Use getList().add()

}
Run Code Online (Sandbox Code Playgroud)

我使用一个简单的 MapperUtils 来映射实体和 dto

public class MapperUtils {

    private static ModelMapper modelMapper = new ModelMapper();

    static {
        modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE);
    }

    private MapperUtils() {
    }

    public static <D, T> D map(final T entity, Class<D> outClass) {
        return modelMapper.map(entity, outClass);
    }

    public static <D, T> List<D> mapAll(final Collection<T> entityList, Class<D> outCLass) {
        return entityList.stream().map(entity -> map(entity, outCLass)).collect(Collectors.toList());
    }

    public static <S, D> D map(final S source, D destination) {
        modelMapper.map(source, destination);
        return destination;
    }

}
Run Code Online (Sandbox Code Playgroud)

那么如果Entity.XXXX是一个Collection,如何使用ModelMapper来使用DTO.getXXXX.add()呢?

小智 5

我不知道 ModelMapper 是否能够支持在映射期间对目标进行 getList().add() 调用。

这里有两种方法可能会解决您的问题。

方法一:启用字段匹配

modelMapper.getConfiguration()
    .setFieldAccessLevel(AccessLevel.PRIVATE)
    .setFieldMatchingEnabled(true);
Run Code Online (Sandbox Code Playgroud)

方法二:

尝试使用 wsimport 生成 setter 代码。