How to map collections in Dozer

前端 未结 8 763
悲&欢浪女
悲&欢浪女 2020-12-14 17:25

I\'d like to do something like:

ArrayList objects = new ArrayList();
...
DozerBeanMapper MAPPER = new DozerBeanMapper         


        
8条回答
  •  难免孤独
    2020-12-14 17:47

    I have done it using Java 8 and dozer 5.5. You don't need any XML files for mapping. You can do it in Java.

    You don't need any additional mapping for lists, only thing you need is

    you need to add the list as a field in the mapping

    . See the sample bean config below.

    Spring configuration class

    @Configuration
    public class Config {
    
    @Bean
        public DozerBeanMapper dozerBeanMapper() throws Exception {
            DozerBeanMapper mapper = new DozerBeanMapper();
            mapper.addMapping( new BeanMappingBuilder() {
                @Override
                protected void configure() {
                    mapping(Answer.class, AnswerDTO.class);
                    mapping(QuestionAndAnswer.class, QuestionAndAnswerDTO.class).fields("answers", "answers");                  
                }
            });
            return mapper;
        }
    
    }
    

    //Answer class and AnswerDTO classes have same attributes

    public class AnswerDTO {
    
        public AnswerDTO() {
            super();
        }
    
        protected int id;
        protected String value;
    
        //setters and getters
    }
    

    //QuestionAndAnswerDTO class has a list of Answers

    public class QuestionAndAnswerDTO {
    
        protected String question;
        protected List answers;
    
       //setters and getters
    }
    

    //LET the QuestionAndAnswer class has similar fields as QuestionAndAnswerDTO

    //Then to use the mapper in your code, autowire it

    @Autowired
    private DozerBeanMapper dozerBeanMapper;
    // in your method
    
    
     QuestionAndAnswerDTO questionAndAnswerDTO =
        dozerBeanMapper.map(questionAndAnswer, QuestionAndAnswerDTO.class);
    

    Hope this will help someone follow the Java approach instead of XML.

提交回复
热议问题