亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

開心每一天1111 2021-08-04 17:51:52
我正在使用 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()}我使用一個簡單的 MapperUtils 來映射實體和 dtopublic 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;    }}那么如果Entity.XXXX是一個Collection,如何使用ModelMapper來使用DTO.getXXXX.add()呢?
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

我不知道 ModelMapper 是否能夠在映射期間支持通過目的地調用 getList().add() 。


這里有 2 個方法可以解決您的問題。


方法一:啟用字段匹配


modelMapper.getConfiguration()

    .setFieldAccessLevel(AccessLevel.PRIVATE)

    .setFieldMatchingEnabled(true);

方法二:


嘗試使用 wsimport 生成 setter 代碼。


查看完整回答
反對 回復 2021-08-04
  • 1 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號